I understand that ValueEventListener runs in a new thread, should I remove it at any point for proper thread management? (e.g. not to have too many threads running in parallel). If yes, how to do it?
When it comes to listeners, yes, you need to remove them according to your activity lifecycle, and for this, you need to use the following line of code:
databaseReference.removeEventListener(valueEventListener);
Remember, if you don't, you'll waste battery power and bandwidth. So:
- If you added a listener in onStart, you must remove it in onStop.
- If you added a listener in onResume, you must remove it in onPause.
- If you added a listener in onCreate, you must remove it in onDestroy.
But remember, onDestroy is not always called, so the last option is not always a good choice.
There is another approach where there is no need to remove the listener, namely when using addListenerForSingleValueEvent:
Add a listener for a single data change at this location.
So, in Indonesian, you can express it as follows:
// When adding a listener in onStart databaseReference.removeEventListener(valueEventListener); // Should be removed in onStop // When adding a listener in onResume databaseReference.removeEventListener(valueEventListener); // Should be removed in onPause // When adding a listener in onCreate databaseReference.removeEventListener(valueEventListener); // Should be removed in onDestroy (but onDestroy is not always called)
Note that using addListenerForSingleValueEvent can be an alternative where you don't need to explicitly remove the listener.