pantos27
pantos27

Reputation: 629

Where to remove a ValueEventListener from on Firebase databse?

Let's say I have a ValueEventListener that listens to a certain query

 val reference = FirebaseDatabase.getInstance().getReference(FirebaseConstants.ARCHIVE)
        reference.orderByKey().limitToLast(30).addValueEventListener(archiveListener)

Do I need to remove the listener from the query itself, like so

FirebaseDatabase.getInstance().getReference(FirebaseConstants.ARCHIVE).orderByKey().limitToLast(30).removeEventListener(archiveListener)

or would removing from the reference object will do? like so

FirebaseDatabase.getInstance().getReference(FirebaseConstants.ARCHIVE).removeEventListener(archiveListener)

Upvotes: 1

Views: 540

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138969

The common practice in Firebase is to remove the listener accordingly to the life-cycle of your activity using the following line of code:

databaseReference.removeEventListener(valueEventListener);
  1. If you have added the listener in onStart method you have to remove it in onStop method .
  2. If you have added the listener in onResume method you have to remove it in onPause method .
  3. If you have added the listener in onCreatemethod you have to remove it in onDestroymethod .

But remember onDestroy is not always called.

If you are using addListenerForSingleValueEvent() it means that OnDataChange() method executes immediately and after executing that method once it stops listening to the reference location it is attached to. So in this case there is no need to remove the listener.

Upvotes: 2

Related Questions