Reputation: 842
I am trying to do something like this for my app:
snapshotListeners() {
firestore()
.collectionGroup()
.where()
.onSnapshot({
error: //Handle error
next: firstSnapshot => {
firstSnapshot.docsChanges().forEach(change => {
//Data retrieved and used in the below query to get more data
firestore()
.collection()
.where() //using the data retrived from the above query here.
.onSnapshot({
error: //Handle error
next: secondSnapshot => {
secondSnapshot.docsChanges().forEach(change =>{
//More Data from second query
})
}
})
})
}
})
}
The second query is dependent on the data retrieved from the first one, and I wish to listen for changes across both queries in their respective documents.
For example, Group Functionality: This is my db structure:
Groups(top-level collection)
|_groupId(documents) - Members(subcollection)
|_groupId | |_uid(document)
| |_uid
|
|__groupdata(Fields like title, description, etc)
So I will use the first listener
to listen for changes to the documents of that particular user in the Members sub-collection and the second listener
for retrieving the groups(data about the groups) he is in realtime so that when he is added/removed from the group, the list/frontend automatically updates just like WhatsApp.
Or even if the group data is changed like the title, description, etc. those changes are heard and updated in the front-end.
Is this nesting of snapshot listeners recommended for this use case or there is another way?
Help would be very much appreciated.
Upvotes: 1
Views: 1510
Reputation: 599776
Nesting listeners like this is quite normal and, when done at a reasonable scale, not a concern. What is reasonable is a bit subjective and dependent, but let's say: something that fits on a single screen in a mobile app is probably a reasonable cap.
Keep in mind that you'll need to manage the listener yourself though. So keep a list of nested listeners you've added, and only add the new ones when the outer listener fires (and remove the outdated ones).
If you want something that scale further, you can duplicate the relevant data from each member (the nested documents) into the group (the parent document).
As a third alternative, you can create a separate subcollection for just the members of a particular group, so that you can listen to all of them with a single snapshot listener.
Upvotes: 1