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).
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();
}
}