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?
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:
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.