1

I have a question regarding QuerySnapshot. For example, lets say I have a chat app. To keep the discussion updated I use a StreamBuilder connected to Firestore. I use a querySnapshot to retrieve all the documents in the collection "messages" and every time I add a message a new Query Snapshot is triggered with the new message and all the previous documents. So here is my question, If my collection "messages" contain 10 documents, the first time I have to get all document so I read 10 documents. Next I add a messag, I now have 11 documents in my collection and the querySnapshot will then return the 11 documents even if I only need the new one. So in the end, will it count as 11 documents read (10 + the new one ) or 21 (10 +11 ) ? If it is the lattest, is there a way to only get the new document instead of all the documents ?

Thanks in advance.

2 Answers2

2

It depends if you have setup a listener .addSnapshotListener or if you have just used .getdocument. If you have set up a listener it will read only new or changed documents from Firestore and then merges it with the locally cached data. It will then present your app with the full 11 documents again though. 10 from the local cache, 1 loaded new. You do have the option to only get the changes, see below. If you didn't set up a listener you can just changed .getdocument with .addSnapshotListener, the rest of the code should be the same. Don't forget to detach the listener when it"s not longer needed though.

db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
    guard let snapshot = querySnapshot else {
        print("Error fetching snapshots: \(error!)")
        return
    }
    snapshot.documentChanges.forEach { diff in
        if (diff.type == .added) {
            print("New city: \(diff.document.data())")
        }
        if (diff.type == .modified) {
            print("Modified city: \(diff.document.data())")
        }
        if (diff.type == .removed) {
            print("Removed city: \(diff.document.data())")
        }
    }
}
Marco Boerner
  • 1,243
  • 1
  • 11
  • 34
1

For as long as a listener is attached to a query, no documents will be re-read from the server as long as they are unchanged. The listener is delivered the entire set for every change, but they are being delivered from memory if they are not changed. You are only getting the changes with each callback, and you can even check to see exactly what changed each time.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • but the `change.doc.data()` gives the full document data and not the change fields/data. Is there a way I can get the old document content? – Vishal Singh Aug 29 '22 at 11:04