Reputation: 518
In Android, when an Activity is destroyed, should I remove all the listeners
ref.addAuthStateListener(listener);
ref.addListenerForSingleValueEvent(listener);
ref.addChildEventListener(listener);
ref.addValueEventListener(listener);
using ref.removeEventListener(listener)
or they will be destroyed automatically?
I know that for FirebaseRecyclerAdapter
we can use cleanup()
to do the job.
Besides listeners and adapters are there any other objects that we need to cleanup?
Upvotes: 5
Views: 4169
Reputation: 493
I had the same issue and was causing a lot of memory leaks. So I created a new class that handles added listeners and removes them when the corresponding method (onPause(), onStop() or onDestroy()) is called. Uses the androidx.lifecycle library and is applicable to both activities and fragments (in fact, any class that implements LifecycleOwner).
You can check the code here. You will probably be good to go without manually adding the androidx.lifecycle dependency, but you can also add this to your module-level build.gradle:
implementation 'androidx.lifecycle:lifecycle-runtime:VERSION'
In your current code, instead of:
databaseReference.addValueEventListener(valueEventListener);
// or
databaseReference.addListenerForSingleValueEvent(valueEventListener);
you need to use:
addValueEventListener(databaseReference, valueEventListener);
// or
addListenerForSingleValueEvent(databaseReference, valueEventListener);
This is valid when called from activities or fragments that use FirebaseListenerHandler, as shown in the gist. If you need to add a Firebase listener in another situation (like services), you still have to manually remove them.
Upvotes: 0
Reputation: 598847
Firebase listeners are not automatically removed. You will indeed have to remove them by calling removeEventListener()
, just like you add them.
Whether you remove listeners in onDestroy()
really depends on where you add them. I typically remove them in the event that is the opposite of where I add them. So if I add then in onCreate()
, I remove then (or call cleanup()
in onDestroy()
. Similar for onStart()
/onStop()
and onPause()
/onResume()
.
Upvotes: 7