How to remove listener for DocumentSnapshot events (Google Cloud FireStore)

Minh Nguyen picture Minh Nguyen · Oct 9, 2017 · Viewed 19.6k times · Source

I'm new in Google Cloud FireStore.

The Document object has a function call onSnapshot to attaches a listener for DocumentSnapshot events.

Is there a function to remove that listener (like offSnapshot)? If not how can I implement it?

Answer

Scarygami picture Scarygami · Oct 9, 2017

In case of the web and node.js SDK, calling onSnapshot returns a function that you need to save in a variable and call when you want to remove the listener.

var unsubscribe = db.collection("cities").onSnapshot(function (querySnaphot) {
  // do something with the data.
});


// Stop listening to changes
unsubscribe();

The other SDKs offer similar functionality.

See https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener for reference.