Home > Blockchain >  Does the Firestore SDK creates multiple listeners for same query?
Does the Firestore SDK creates multiple listeners for same query?

Time:03-14

private loadData(): void {
    const q = query(collection(this.store, 'users'), orderBy('userName'));
    this.unsubscribe = onSnapshot(q, p => {
        let users: any[] = [];
        p.forEach(x => {
            users.push(x.data());
        });
        this.usersDataSource = users;
    });
}

In the above method a listener is being created, and it can be removed the listener by calling -

this.unsubscribe();

On the same page/component, if this method gets called multiple times, does Firebase creates new listener each time? If yes, then what is the best way to remove all those listeners?

CodePudding user response:

It seems your question is around having to remove each listener you register, which indeed you have to do.

While the SDK may deduplicate the listeners to the backend (it may, but I actually haven't checked in a while) that is unrelated to the API exposed to you: the number of calls to subscribe a listener must be balanced with the number of calls to unsubscribe it before the SDK will stop listening for changes on the server.

I typically keep a list of unsubscribe method for each scope of my application that I need to unsubscribe when the scope changes. So for example, if I have a React app, I do this per component. In other frameworks, the route-change logic is usually a good place to unsubscribe listeners from the old route.

  • Related