Search code examples
javascriptfirebasegoogle-cloud-firestorelistenerreal-time-updates

Remove a realtime listener on firestore


I am kinda new on firebase and I don't quite understand how to detach a realtime listener. I already read the official documentation but still don't understand how to. If anyone could simplify it for me and create a function to start the listener and another one to stop it, it would be really awesome.

To start the listener I need just to call start()

function start(){
  firebase.firestore().doc("users/x").onSnapshot(function(doc) {
   console.log(doc.data());
  });
}

But to stop the listener I tried to call the function with noting in it, however it doesn't work

//Doesn't work
function stop(){
 firebase.firestore().doc("users/x").onSnapshot(function(doc) {
   //Not putting anything in here
  });
 }

Solution

  • The following should do the trick:

    var fbListener = null;
    
    function start(){
      fbListener = firebase.firestore().doc("users/x").onSnapshot(function(doc) {
       console.log(doc.data());
      });
    }
    
    function stop(){
      fbListener();
    }
    

    Have a look at the docs here and here: onSnapshot returns "an unsubscribe function that can be called to cancel the snapshot listener".