【发布时间】:2020-11-29 06:46:03
【问题描述】:
我正在尝试使用 Flow Coroutines 获取 authStateListener 的 liveStatus。但每次它返回 False。下面是我尝试实现的代码。它遵循 MVVM 模式。
代码 -> Firebase 用户流
open class FirebaseUserFlow() {
private val firebaseAuth = FirebaseAuth.getInstance()
private var auth: FirebaseUser? = null
@ExperimentalCoroutinesApi
fun getUserInfo(): Flow<FirebaseUser?> =
callbackFlow {
val authStateListener = FirebaseAuth.AuthStateListener {
auth = it.currentUser
}
offer(auth)
firebaseAuth.addAuthStateListener(authStateListener)
awaitClose {
firebaseAuth.removeAuthStateListener(authStateListener)
}
}
}
视图模型
class AuthViewModel : ViewModel() {
enum class AuthenticationClass {
AUTHENTICATED,
UNAUTHENTICATED
}
@ExperimentalCoroutinesApi
val authenticationState = FirebaseUserFlow().getUserInfo().map {
Log.d("Tag","The value of the user is $it")
if (it != null) {
AuthenticationClass.AUTHENTICATED
} else {
AuthenticationClass.UNAUTHENTICATED
}
}.asLiveData()
}
上面的日志总是返回false
片段
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.authenticationState.observe(viewLifecycleOwner, Observer {authenticationstate ->
when (authenticationstate) {
AuthViewModel.AuthenticationClass.AUTHENTICATED -> {
findNavController().navigate(R.id.action_loginFragmentUser_to_homeFragment)
Log.d("TAG","Authenticated")
}
else -> Log.d("TAG","Else")
}
})
}
在上面的片段中,在 onActivityCreated 中观察到 liveData 并根据它导航到主页片段的状态。
【问题讨论】:
标签: android kotlin mvvm firebase-authentication kotlin-coroutines