4

I am trying to send multiple requests to Firestore at the same time. I need to retrieve multiple objects at a time, the requests are not currently possible with one Query, because they are at separate locations and Firestore does not yet have querying multiple locations or an equivalent to the IN operator in SQL.

I know from this question, Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly that Firebase can pipeline queries together because it uses one connection, but I cannot find any content on how to do so in android.

So, how do I properly pipeline Firestore requests in Android?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
DJ-ST
  • 129
  • 10
  • Are you just trying to fetch a bunch of documents a single time, and continue when all of the documents are available? If so, your answer below is way too complex and too many lines of code. – Doug Stevenson Mar 10 '18 at 03:25

1 Answers1

5

If you just want to get a bunch of documents a single time (not listening to changes), then you just need to use the get() method on each DocumentReference that you want. Each of these calls to get() returns a Task whose listeners will be invoked with the results. A Task is like a Future or a JavaScript Promise - it's what the Play Services uses for async programming.

If you want to wait until all of the calls to get are done, simply collect all those Task objects in a List, then pass that to Tasks.whenAll() to know when everything is done. That will return another Task that's successful only after all the other tasks are successful. You can then reach into all the other tasks to get the document contents.

You should be aware also that the code you're using sets up listeners to changes in the documents, and they will continue to fire when the documents change at the server. If you don't remove those listener, you will incur extra data costs, and also leak the listeners.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441