Should I actually remove the ValueEventListener?

DatabaseReference Ref = FirebaseDatabase.getInstance().getReference(Constants.Client + "/" + path); Ref.keepSynced(true); Ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { } @Override public void onCancelled(DatabaseError databaseError) { } }); 

I understand that a ValueEventListener working in a new thread, should I actually delete this at any point in time to properly manage the threads? (example for not too many threads working in parallel). If so, how to do it?

0
java android multithreading firebase firebase-database firebase-realtime-database
source share
2 answers

Speaking of listeners, yes, you need to remove them according to the life cycle of your activity, and for this you need to use the following line of code:

 databaseReference.removeEventListener(valueEventListener); 

Remember that if you do not, you will end up wasting battery and traffic. So:

  1. If you added a listener to onStart you must delete it in onStop .
  2. If you added a listener to onResume you must remove it in onPause .
  3. If you added a listener to onCreate you must remove it to onDestroy .

But remember that onDestroy 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 one data change at this location.

+5
source share

To remove a ValueEventListener, you can do the following:

Remove listener anonymity.

Change the code:

  Ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { } @Override public void onCancelled(DatabaseError databaseError) { } }); 

in it:

  ValueEventListener listener= new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { } @Override public void onCancelled(DatabaseError databaseError) { } }); Ref.addValueEventListener(listener); 

Now you can remove the listener:

  @Override public void onDestroy() { if (Ref != null && listener != null) { Ref.removeEventListener(listener); } } 

You need to remove it so that the listener does not remain included in other action life cycles such as onDestroy()

+3
source share

All Articles