How does Firestore document snapshot work?

Viewed 4971

when a new document is added, snapshot fetches all the documents including the new ones or only the newly added ones ? If it fetches all the documents every time then it will add to the billing cost. How to get around this problem ?

StreamBuilder(
          stream:Firestore.instance
              .collection('chat')
              .orderBy('timeStamp', descending: true).snapshots(),
          builder: (context, streamSnapshot) {}
);
2 Answers

While your snapshots() listener stays active, the server actively monitors for changes that are relevant to your listener. When there are such changes it only sends you new documents, or documents that were changed, to your client. The client then merges those updates with its local data, and presents you with a new complete QuerySnapshot.

According to the official doc : Here

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries:

  • Call a method to get the data.
  • Set a listener to receive data-change events.

When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.

You can get an array of the document snapshots by using the docs property of a QuerySnapshot. After that you'll have to loop through getting the data of the doc snapshots looking for your doc.

OR if you don't actually need the full QuerySnapshot, you can apply the filter using the where function before calling get on the query object

These are the most efficient way to get documents.

Related