Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to prevent memory-leak when using Firebase

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?

like image 994
Andre Haueisen Avatar asked Mar 12 '23 17:03

Andre Haueisen


1 Answers

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().

like image 81
Frank van Puffelen Avatar answered Mar 23 '23 17:03

Frank van Puffelen