yotam hadas
yotam hadas

Reputation: 873

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?

Upvotes: 5

Views: 2031

Answers (1)

Ryan Pierce
Ryan Pierce

Reputation: 1633

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();
}

Upvotes: 1

Related Questions