I have a flutter app running the following query:
Future<QuerySnapshot<Object?>> getPendingDiscoveryChats(
String userId, DocumentSnapshot? lastDocument) async {
QuerySnapshot result;
if (lastDocument == null) {
result = await FirebaseFirestore.instance
.collection('discoveryChats')
.where('senderId', isEqualTo: userId)
.where('pending', isEqualTo: true)
.orderBy('lastMessageSentDateTime', descending: true)
.limit(10)
.get();
} else {
result = await FirebaseFirestore.instance
.collection('discoveryChats')
.where('senderId', isEqualTo: userId)
.where('pending', isEqualTo: true)
.orderBy('lastMessageSentDateTime', descending: true)
.startAfterDocument(lastDocument)
.limit(10)
.get();
}
return result;
}
This gets me a list of chats. This query is first ran when the screen is loaded, but there is a refresh indicator aswell to call for updates. So my question is this: say there is the case where ten documents are loaded, and a new one is added. When the refresh occurs, the query gets 1 new document, and 9 unchanged ones. Did the 9 unchanged documents come from the cache, or did they cost me reads?
And another case is where the refresh occurs when no changes happens. Does Firestore charge me 10 reads to confirm the results are all the same values?
Thank you!
CodePudding user response:
Anytime there is a refresh and get() is called, you are charged for 10 reads because that is what get() returned for the query. It is irrelevant that they are in cache because, as you said, there were still reads to confirm the values are the same.
I would recommend you make use of Streams to allow for instant updating anytime something in the query changes without the user needing to refresh. This is also more read efficient and is best practice. Below is the example from the documentation
Stream collectionStream = FirebaseFirestore.instance.collection('users').snapshots();
Stream documentStream = FirebaseFirestore.instance.collection('users').doc('ABC123').snapshots();