问题
Why do the Firebase authentication patterns use
auth = FirebaseAuth.getInstance();
auth.<signin type>.addOnCompleteListener
Instead of adding the onCompleteListener to the auth object before making the authentication attempt? Isn't there a race condition if one does not use:
auth.addOnCompleteListener(...)
auth.<signon attempt>
回答1:
When you start a sign-in flow, it returns a task. That task completes when the auth flow completes (either successfully or with an error). It's a promise-like API, which means that you can add the completion listener late and it will still be invoked.
I prefer using an AuthStateListener
myself though:
auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
setCurrentUser(firebaseAuth.getCurrentUser());
}
});
The onAuthStateChanged()
method will be called immediate with the current auth state and then whenever the auth state changes. This removes any fear for race conditions from my mind and makes my code very "reactive".
I think we internally called these time-varying values, but am not sure if that's also the more general term for them.
来源:https://stackoverflow.com/questions/37424625/why-is-the-firebase-authentication-method-call-patttern-used