Firebase Android onAuthStateChanged called twice

前端 未结 6 1138
忘了有多久
忘了有多久 2020-12-02 20:16

I\'ve start working with new Firebase SDK.

When I\'m doing user login, I\'m onAuthStateChanged method is being called twice with same state (etc. user sign in).

6条回答
  •  孤街浪徒
    2020-12-02 20:30

    Usually I want to setup the UI before adding the listener and repeat the setup any time the auth state changes (avoiding the initial double call). My solution is to enhance the boolean flag solution and keep track of the uid (not the token) of the last user, which may be null.

    private FirebaseAuth firebaseAuth;
    private String lastUid; // keeps track of login status and changes thereof
    

    In onCreate, I get the auth instance and set the UI accordingly, before adding the listener in onStart

    @Override
    protected void onCreate(Bundle savedInstanceState){
        ...
        firebaseAuth = FirebaseAuth.getInstance();
        getUserSetUI();
        ...
    }
    

    where getUserSetUI sets lastUid according to the auth instance

    private void getUserSetUI(){
        lastUid = (firebaseAuth == null || firebaseAuth.getCurrentUser() == null) ?
                null : firebaseAuth.getUid();
        setUI(!(lastUid == null));
    }
    

    The listener checks to see if the state has actually changed

    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth auth){
        String uid = auth.getUid(); // could be null
        if( (uid == null && lastUid != null) || // loggedout
                (uid != null && lastUid == null) || // loggedin
                (uid != null && lastUid != null && // switched accounts (unlikely)
                        !uid.equals(lastUid))){
            getUserSetUI();
        }
    }
    

提交回复
热议问题