I am implementing a "My Chats" screen. I am interesting into listening all the new changes on my chats, without downloading the entire collection.
In order to do that, I have decided to order my queries by date fields.
This is how a chat room doc looks in my system:
doc {
...
deletedAt: null | date,
lastMessage: {
...,
date: date,
deletedAt: null | date,
},
readAt: null | date,
}
I have different types of "events" that I need to listen to:
Listen to new chat rooms (a new chat room will contain, for sure, a lastMessage.date field)
Listen to chatRoom.readAt updates
Listen to chatRoom.deletedAt updates
Listen to lastMessage.deletedAt updates
Listen to new lastMessage.date updates
In order to listen to new chats, I am doing:
firestore
.collection("chats")
.where("membersArray", "array-contains", currentUser.uid)
.where("deletedAt", "==", null)
.orderBy("lastMessage.date")
.startAt(new Date())
.onSnapshot(...);
And, in order to listen to "readAt" changes, after new Date() and without the need of downloading the entire collection, I am doing:
firestore
.collection("chats")
.where("membersArray", "array-contains", currentUser.uid)
.where("deletedAt", "==", null)
.orderBy("readAt")
.startAt(new Date())
.onSnapshot(...);
Both listeners work good. But... as I need to detect all the changes in the same screen, there may be intersections between the results of both listeners.
This is the only way I can think of to listen to the different types of events in my collection and from a specific date, without having to read all the documents.
Is there a way to avoid all these possible intersections? Or to listen to all these different events at once, without the need to create different listeners or to read the entire collection?
Note: I am using querySnapshot.docChanges() in order to get changes.
Both queries seem to read the exact same set of documents, only in a different order. In such a case, I'd typically read the documents with only one query, and then re-order them as needed in my application code.