Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove listener from Firebase Realtime Database

For receiving data from Firebase Realtime Database I need to register listener:

objectReference.addValueEventListener(valueEventListener);

What is correct way to remove (unregister) this listener?

like image 390
tse Avatar asked Nov 07 '17 13:11

tse


People also ask

How do I get rid of Firebase listener?

Detach listeners Callbacks are removed by calling the off() method on your Firebase database reference. You can remove a single listener by passing it as a parameter to off() . Calling off() on the location with no arguments removes all listeners at that location.

How do I delete a child from Firebase?

How do I remove a child from Firebase? The simplest way to delete data is to call remove() on a reference to the location of that data. You can also delete by specifying null as the value for another write operation such as set() or update() .

How do you delete data from Firebase realtime database?

The simplest way for deleting data is to call removeValue() on a reference to the location of that data. We can also delete data by specifying null as the value for another write operation such as setValue() or updateChildren().

What is Firebase listener?

Firebase utilizes listeners to watch for changes in a specified node. It is similar to an event handler in the sense that a code is triggered based on a certain circumstance. In our case, whenever changes in that node's data occur, the listener automatically provides the application updated data, called a snapshot.


2 Answers

The correct way to remove a listener is to remove it accordingly to the life-cycle of your activity using this line of code:

databaseReference.removeEventListener(valueEventListener);

Note that, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.

But remember onDestroy is not always called.

like image 169
Alex Mamo Avatar answered Sep 19 '22 17:09

Alex Mamo


Its better to check whether listener is null or has an object, because if the listener object is null there will be a runtime error

if(valueEventListener!=null){
  databaseReference.removeEventListener(valueEventListener);
}
like image 30
Lasitha Lakmal Avatar answered Sep 18 '22 17:09

Lasitha Lakmal