0

what happens when ValueEventListener is not removed when activity is destroyed. Does this event listener listen even after activity destroys?

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
                \\todo
        }});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Yash
  • 211
  • 2
  • 14
  • If `myRef` isn't destroyed, and there is an active listener with some changed data, `onDataChange()` might be called. If it is called, your code will execute. If you access `context` here, it will crash because Activity & context was destroyed. – rupinderjeet Aug 28 '20 at 13:08
  • You can also check **[this](https://stackoverflow.com/a/48862873/5246885)** out. – Alex Mamo Aug 29 '20 at 09:20

2 Answers2

1

Firebase Realtime Database listeners are not automatically scoped to the context/activity. So the listener will indeed remain active until you explicitly remove it, or until the application exits.

If the code in your onDataChange accesses the UI elements of the activity, this may lead to unexpected results and crashes. For this reason it is common to remove the listener in a lifecycle event, such as onStop or onPause.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

If you don't remove the listener, then it will keep on listening. You will effectively "leak" the listener if you don't remove it when it's no longer needed. The listener knows nothing about the Android activity lifecycle, so you have will have to add code to remove it at the right time.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441