Sipan Hazim
Sipan Hazim

Reputation: 47

does Cloud Firestore realtime listener get all document from server when only one document change?

In my code I have listener that listen to 7 document.

Firestore.firestore()
            .collection(FirestorePaths.days)
            .whereField(DayKeys.date, in: CalendarService.shared.currentWeek)
            .whereField(DayKeys.fieldId, isEqualTo: "JAfWuBindnh4jIfsVGh4Vl3AvfU2")
            .addSnapshotListener { querySnapshot, error in

                if let error = error {
                    print(error)
                    return
                }
                
                querySnapshot?.documentChanges.forEach { diff in
                           if (diff.type == .added) {
                               print("New day: \(diff.document.data())")
                           }
                           if (diff.type == .modified) {
                               print("Modified day: \(diff.document.data())")
                           }
                           if (diff.type == .removed) {
                               print("Removed day: \(diff.document.data())")
                           }
                       }
                
                _ = querySnapshot?.documents.compactMap {
                    print($0.metadata.isFromCache ? "Cache" : "Server")
                }
                
            }

but when one document change from server side i get this message:

Modified day ...

    Server
    Server
    Server
    Server
    Server
    Server
    Server

so I'm wondering does its count 7 read or only one read?

Upvotes: 0

Views: 143

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598916

When any document for your snapshot listener changes, your code gets called again with a query snapshot with all documents, but you only get charged for the documents that had to be read from/on the server for that. So if only one document changed, you'll only get charged for that one document.

The metadata field isFromCache is confusingly named, but actually signals where the document snapshot may contain data that is not up to date with the server. So it's better to read it as "may contain stale data", which is not the case here for any of the documents.

Upvotes: 1

Related Questions