How to detach firestore listener

ListenerRegistration is the Key

If you want to start and stop Realtime Updates from a FirebaseDatabase then you should register and unregister your EventListners with ListenerRegistration.

Full Code:

MyActivity extends AppCompatActivity implements EventListener<QuerySnapshot>{

      private CollectionReference collectionRef; //<- You will get realtime updates on this
      private ListenerRegistration registration;

      public void registerListner(){
           registration = collectionRef.addSnapshotListener(this);      
      }

      public void unregisterListener(){
           registration.remove();           //<-- This is the key
      }


      @Override
      public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {

          for(DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()){

              Log.d("Tag",  dc.getType().toString()+" "+dc.getDocument().getData());
        
          }
      }

}

When you use addSnapshotListener you attach a listener that gets called for any changes. Apparently you have to detach those listeners before the activity gets destroyed. An alternative is to add the activity to your call to addSnapshotListener:

 db.collection("Pessoa").document(paciente.getProfissionalResponsavel())
   .addSnapshotListener(MainActivity.this, new EventListener<DocumentSnapshot>() {

You'll need to update MainActivity.this to match your code.

By passing in the activity, Firestore can clean up the listeners automatically when the activity is stopped.

Yet another alternative is to use get() to get those nested documented, which just reads the document once. Since it only reads once, there is no listener to clean up.


use registration.remove(); for Stop listening to changes

Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
        new EventListener<QuerySnapshot>() {
            // ...
        });

// ...

// Stop listening to changes
registration.remove();

see more about this : https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener