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

查看:16
本文介绍了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)

上面,我在一个单独的执行器上运行一个 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天全站免登陆