I'm trying to observing sign-in state with below code,
@HiltViewModel
class LoginViewModel @Inject constructor(
private val auth: FirebaseAuth,
):ViewModel(){
fun getUser():MutableLiveData<FirebaseUser?>?{
return MutableLiveData(auth.currentUser)
}
}
and obeserving it in Fragment
@AndroidEntryPoint
class SettingFragment : Fragment() {
//..
binding.apply {
LoginViewModel.getUser()?.observe(viewLifecycleOwner){
when(it){
null -> isSignedIn = false
else -> isSignedIn = true
}
}
}
//..
}
The problem is observe
detect when FirebaseUser
became null
(when signed-out),
but doesn't detect when signed-in.
I don't know why it works like this..
CodePudding user response:
Your LiveData will only ever produce one value:
MutableLiveData(auth.currentUser)
That is, the value of auth.currentUser
at the time the object was constructed (null). It's not "listening" to anything at all, and not responding to any changes in the user's auth state.
If you want to respond to changes in auth state, you will need to use an AuthStateListener, and use its callbacks to push new values into the LiveData.
See: