Firebase Firestore同步/不带回调地检索数据 [英] Firebase Firestore retrieve data Synchronously/without callbacks

查看:96
本文介绍了Firebase Firestore同步/不带回调地检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android应用程序的单独线程中使用Cloud Firestore,所以我不想使用侦听器OnSuccessListenerOnFailureListener在另一个线程中运行.我可以让我的线程等待结果(并在需要时捕获任何异常)吗?

I am using Cloud Firestore in a separate thread in my Android app, so I don't want to use listeners OnSuccessListener and OnFailureListener to run in yet another thread. Can I just make my thread wait for the result (and catch any exceptions if needed)?

当前用于查询的代码如下:

Currently the code for querying is something like this:

FirebaseFirestore.getInstance().collection("someCollection").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot documentSnapshots) {
         // do something on the UI thread with the retrieved data
         }
    });

我想要拥有的东西:

FirebaseFirestore.getInstance().collection("someCollection").getAndWaitForResult();
//Block the thread and wait for result, no callbacks. 
//getAndWaitForResult() is not a real function, just something to describe my intention.

以前我曾经使用过Parse Server,在那儿这很琐碎.

I used to work with Parse Server before, and it was quite trivial there.

推荐答案

您可以同步加载数据,因为DocumentReference.get()返回Task. 因此,您可以等待该任务.

You can synchronously load data, because a DocumentReference.get() returns a Task. So you can just wait on that task.

如果我做类似的事情:

    val task: Task<DocumentSnapshot> = docRef.get()

然后我可以等待完成

val snap: DocumentSnapshot = Tasks.await(task)

当在get()之后继续进行其他操作(可能需要一点时间)时,这很有用:

This is useful when piplining other operations together after the get() with continuations which may take a little while:

val任务:Task = docRef.get().continueWith(executor,continuation)

val task: Task = docRef.get().continueWith(executor, continuation)

上面,我正在一个单独的执行程序上运行延续,并且我可以等到所有这些都通过Tasks.await(task)完成.

Above, I am running a continuation on a separate executor, and I can wait for it all to complete with Tasks.await(task).

请参见 https://developers.google.com/android/guides/tasks

注意:您不能在主线程上调用Tasks.await(). Tasks API专门检查这种情况,并会引发异常.

Note: You can't call Tasks.await() on your main thread. The Tasks API specifically checks for this condition and will throw an exception.

还有另一种使用事务同步运行的方法. 参见此问题.

There is another way to run synchronously, using transactions. See this question.

这篇关于Firebase Firestore同步/不带回调地检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆