Firebase Firestore同步/无回调检索数据

问题描述:

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

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()返回任务
所以你可以等待那个任务。

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任务:任务= docRef.get()。continueWith(executor,continuation)

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

上面,我在一个单独的执行器上运行了一个延续,我可以等待它全部完成 Tasks.await(任务)

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.