Reputation: 1533
I've just started with firebase in android and i can't understand some things in onStart and in onStop.
Why is it necessary to have this code on stop method? Why do we need to remove listener ?
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
if(mAuthStateListener != null)
mAuth.removeAuthStateListener(mAuthStateListener);
}
And one more question what is the advantage of setting up mAuth listener in onStart method instead of onCreate ?
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
mAuth.addAuthStateListener(mAuthStateListener);
}
This is how they shoved in Firebase -> Authentication demo.
Upvotes: 2
Views: 1706
Reputation: 271410
There is the need to remove listeners because the mAuth
will keep of keeping track of all the listeners you added, in order to notify you when something happens.
When the activity stops you remove the listener from the list because well, the activity has stopped anyway, there is no need to listen for auth events when the activity is stopped, is there?
Why add the listener at onStart
then?
Because according to the activity life cycle:
onStart
and onStop
correspond to each other, while onCreate
and onDestroy
correspond to each other.
If you add the listener in onCreate
and remove at onStop
, the listener will not be added back when the activity restarts, since onCreate
is not called on restart. onStart
is.
Upvotes: 8