Firebase Firestore retrieve data Synchronously/without callbacks

后端 未结 2 1649
再見小時候
再見小時候 2020-12-09 05:02

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

2条回答
  •  离开以前
    2020-12-09 05:32

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

    If I do something like:

        val task: Task = docRef.get()
    

    then I can wait for it to complete by doing

    val snap: DocumentSnapshot = Tasks.await(task)
    

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

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

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

    See https://developers.google.com/android/guides/tasks

    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.

提交回复
热议问题