Home > Software engineering >  Will this approach of using two queries reduce Firestore read count work?
Will this approach of using two queries reduce Firestore read count work?

Time:10-11

I have a collection called tasks which contains more than 100 documents. App's home screen has a list view which shows a list of all the documents but this approach will unnecessarily cost 100 reads every time a user opens the app. So to stop that I added a field called updated_at to each document which I update every time user updates the task document. So now this is how I build the home screen.

 buildListView() async{
   //get locally stored latest updated_at
   const lastUpdatedAt = getLastUpdatedOfLatestFetchedDoc()
   await firestore.collection('tasks').where('updated_at', '>', lastUpdatedAt).get(source: 'server');
   const docs = await firestore.collection('tasks').get(source: 'cache');
  //Build list using docs array
 }

First query will get only those documents which are updated after the last fetch time from the server. 2nd query will fetch all the documents but from the cache. I don’t care about the result of the 1st query as it may or may not return any documents but if it returns it will anyway store in the cache which 2nd query will include. Will this approach work?

CodePudding user response:

Yeah, the approach should work assuming that you've enabled the disk cache.

It won't significantly reduce the number of document reads on the server however as Firestore already will read un-updated documents from the disk cache anyway if you don't explicitly tell it to get them from the server (as you do here).

I'd also strongly recommend using onSnapshot() to make the user experience smoother, as that pretty much does a more efficient version of your code:

  1. It calls your callback with the documents from the local cache.
  2. It checks with the server if there are any updated/new documents.
  3. It calls your callback again, with the now updated documents from the local cache.

So you'll already be able to paint the data in step 1 here, which typically leads to a better user experience than waiting for the updated data to have loaded.

  • Related