Is it necessary to remove each added listener from Firebase Realtime Database?

765 Views Asked by At

As I know, each attached listener in Firebase Realtime Database must be removed with a call to removeEventListener(). Suppose I attached a listener to a node inside a coroutine, and then later if I cancel the coroutine, then my app would stop listening to the database. For eg:

viewModelScope.launch {
    Firebase.database.reference.child("users").addValueEventListener(usersListener) //usersListener is a ValueEventListener
}

In that case, does listener gets removed? Or there also I should explicitly remove listener? What happens if I don't remove the listeners I attached? How long do they stay there?

2

There are 2 best solutions below

0
On BEST ANSWER

When you are using "addValueEventListener()", it means that you are attaching a persistent listener to a specific location in the database to get data in real-time. It doesn't really matter if you are adding the listener in a Coroutine context or not, you always need to remove the listener accordingly to the lifecycle of your activity.

If you don't need real-time updates, you can use addListenerForSingleValueEvent(), as it:

Adds a listener for a single change in the data at this location.

So there is no need to remove any listener at all.

You can also use the relatively new added get() method, as explained in one of my articles:

What happens if you don't remove the listener?

Then it will always keep on listening. In an Android context, the listener knows nothing about the Android activity lifecycle. So as said above, so you'll have to explicitly remove it at the right time, so it cannot lead to unexpected results and crashes.

1
On

It's not required to remove them as it can throw an error and you can catch the error. However, it is advised to clean up your listeners when you don't need them to prevent them from re-firing as you are typically only removing the reference to that listener.

Technically in the background, each client listens to all 'listen' events through web sockets, and until the listener is unregistered, it will attempt to keep listening with your app's changed state which can lead to higher reads, memory leaks, and performance issues in general.