1

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
  });
 }
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Nimbus321
  • 13
  • 5
  • just directly acess the data from firestore dont use onsnapshot listner https://firebase.google.com/docs/firestore/query-data/get-data check get data section – user13966865 Jul 22 '20 at 11:33
  • I know how to do that, but I require a realtime listener in this case. – Nimbus321 Jul 22 '20 at 11:50

1 Answers1

2

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".

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121