Firebase Firestore retrieve data Synchronously/without callbacks
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<DocumentSnapshot> = 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.