For receiving data from Firebase Realtime Database I need to register listener:
objectReference.addValueEventListener(valueEventListener);
What is correct way to remove (unregister) this 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 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() .
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().
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With