Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase listener need to always be removed?

If I use listener in activity in the following manner:

// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

Attaching an annonymous listener (event that does not attached to variable), do I still need to remove it?

*I set this on the onStart() and need it to run until onStop() / onDestroy()

When is it nessecery to remove the listener?

like image 376
yotam hadas Avatar asked Nov 09 '22 06:11

yotam hadas


1 Answers

If you only want the listener to work while the activity is active, you can detach the listener by invoking the removeEventListener() method on your Firebase database reference. If you attach the listener in your onStart(), then you should detach in onStop().

@Override
protected void onStop() {
    super.onStop();

    //...
    myRef.removeEventListener();
}
like image 96
Ryan Pierce Avatar answered Nov 15 '22 05:11

Ryan Pierce