如何同步读取Firebase实时数据库值? [英] How to read Firebase realtime database value synchronously?
问题描述
我正在使用Firebase实时数据库,据我所知,您必须使用
I'm using firebase realtime database and as far I know, you have to use the
DatabaseReference.addValueEventListener
从firebase数据库中读取一个值.
to read a value from the firebase database.
此处addValueEventListener
在默认情况下是异步的.我需要同步阅读.对于FireBase存储,对于上载文件时的相同问题,我可以使用
Here addValueEventListener
is asynchronous by default. I need to read it synchronously. For FireBase storage, for the same issue while uploading files, I could make the process synchronous by using
UploadTask.TaskSnapshot await = Tasks.await(uploadTask);
代替使用
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
}
})
是否有与上述类似的addValueEventListener
同步替代方案?
Is there any similar synchronous alternative for addValueEventListener
like shown above?
推荐答案
尝试从异步的API同步返回值,这不是一个好主意.但是,如果您的块已经与主线程异步-您可以使用CountDownLatch
和await
回调响应.
Trying to return a value synchronously from an API that's asynchronous, it's not a good idea. But if your block is already asynchronous with main thread - you can use CountDownLatch
and await
callback response.
示例:
CountDownLatch latch = new CountDownLatch(1);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>(){
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
//Handle response
latch.countDown();
}
});
latch.await();
这篇关于如何同步读取Firebase实时数据库值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!