Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore retrieve data Synchronously/without callbacks

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
         }
    });

What I'd like to have:

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.

I used to work with Parse Server before, and it was quite trivial there.

like image 940
Dmitri Borohhov Avatar asked Oct 23 '17 18:10

Dmitri Borohhov


1 Answers

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.

like image 144
Dutch Masters Avatar answered Oct 13 '22 18:10

Dutch Masters