在实施架构组件方面是否有改进的余地或一般考虑:
- 注意:如果您选择使用 AuthStateListener,请确保在启动 FirebaseUI 流程之前取消注册,并在流程返回后重新注册。FirebaseUI 在内部执行身份验证操作,这可能会在流程完成之前触发侦听器。
实时数据
public class FirebaseAuthLiveData extends LiveData<FirebaseUser> {
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener authStateListener =
new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
setValue(firebaseUser);
}
};
@Override
protected void onActive() {
super.onActive();
firebaseAuth.addAuthStateListener(authStateListener);
}
@Override
protected void onInactive() {
super.onInactive();
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
视图模型
public class FirebaseAuthViewModel extends ViewModel {
private final FirebaseAuthLiveData firebaseAuthLiveData = new
FirebaseAuthLiveData();
public LiveData<FirebaseUser> getFirebaseAuthLiveData() {
return firebaseAuthLiveData; }
}
}
主要活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseAuthViewModel firebaseAuthViewModel =
ViewModelProviders.of(MainActivity.this).get(FirebaseAuthViewModel.class);
firebaseUserLiveData = firebaseAuthViewModel.getFirebaseAuthLiveData();
firebaseUserLiveData.observe(MainActivity.this, new Observer<FirebaseUser>() {
@Override
public void onChanged(@Nullable FirebaseUser firebaseUser) {
if (firebaseUser == null) {
final Intent intent = AuthUI.getInstance().createSignInIntentBuilder()
.setAvailableProviders(Collections.singletonList(
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build())
).build();
startActivityForResult(intent, SIGN_IN);
} else {
updateUI(firebaseUser);
}
}
});
}