Firebase Android onAuthStateChanged called twice

Solution 1:

Yes, and this is very annoying. This is due a registration call. Not only that, onAuthStateChanged is going to be called many times in many different states, with no possibility of knowing which state it is.

Documentation says:

onAuthStateChanged(FirebaseAuth auth)

This method 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

Here some tips to discover the current state:

  • Registration call: skip the first call with a flag.
  • User signed in: user from parameter is != null.
  • User signed out: user from parameter is == null.
  • Current user changes: user from parameter is != null and last user id is != user id from parameter
  • User token refresh: user from parameter is != null and last user id is == user id from parameter

This listener is a mess and very bugprone. Firebase team should look into it.

Solution 2:

My workaround is to use a Boolean declared globally to flag if onAuthStateChanged has need called before.

private Boolean authFlag = false;
 mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null) {
                if(authFlag== false) {
                    // Task to perform once
                    authFlag=true;
                }
            }
        }
    };