How does the firebase AuthStateListener work?

15,515

As the Firebase API says:

AuthStateListener is called when there is a change in the authentication state.

OnAuthStateChanged gets invoked in the UI thread on changes in the authentication state:

  • Right after the listener has been registered
  • When a user is signed in
  • When the current user is signed out
  • When the current user changes
  • When there is a change in the current user's token (Notice this has been removed and moved to a separate listener, see FirebaseAuth.IdTokenListener)
Share:
15,515
Tom Finet
Author by

Tom Finet

Updated on June 06, 2022

Comments

  • Tom Finet
    Tom Finet about 2 years

    I am developing an android app using firebase for user management and authentication. I was wondering when the auth state listener gets called and how it works, as in my app I have a bug related to this.

    Here is an example of one in my android app:

    mAuthListener = new FirebaseAuth.AuthStateListener() {
                @Override
                public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    FirebaseUser user = firebaseAuth.getCurrentUser();
                    if (user != null) {
                        // Sign in logic here.
                    }
                }
            };
    

    How does the AuthStateListener work and when does it get called?

  • Tom Finet
    Tom Finet almost 8 years
    Thank you this really helped me understand! =)
  • Firanto
    Firanto over 7 years
    And how does we suppose to know what happen? on each call? The FirebaseAuth instance didn't tell anything except for currentUser (only whether it exist or null).
  • ninbit
    ninbit almost 6 years
    Registering means addAuthStateListener(...) ?
  • payne
    payne almost 6 years
    The documentation does not mention the 5th element listed in the answer ("When there is a change in the current user's token").
  • AL.
    AL. over 4 years
    In response to payne, the 5th item has been removed and and moved to a separate listener FirebaseAuth.IdTokenListener (which still includes the rest of the items). @Ami, would suggest to edit it in your answer? Cheers!