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
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.
Your can do something like this on the main thread...
YourObject yourObject = (YourObject)new RunInBackground().
execute("someCollection","someDocument").get()
And the background thread is...
public class RunInBackground extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
Task<DocumentSnapshot> documentSnapshotTask = FirebaseFirestore.getInstance().
collection((String) objects[0]).document((String) objects[1]).get();
YourObject obj=null;
try {
DocumentSnapshot documentSnapshot = Tasks.await(documentSnapshotTask);
obj = new YourObject();
obj.setter(documentSnapshot.get("your field"));
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return obj;
}
}