我想使用 Kotlin Flow 来处理 FirebaseAuth 状态。我知道下面的代码是错误的,但我不知道如何修复它。我尝试使用 channelFlow
并且当我想要 send
或 offer
fun registerFlow(email: String, password: String) = flow {
emit(AuthState.Loading)
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
CoroutineScope(Dispatchers.IO).launch {
emit(AuthState.Success(task.result?.user))
} }else {
emit(AuthState.Error(task.exception))
}
}
}
}
Listener
里面的协程抛出
z E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: pl.rybson.musicquiz, PID: 26578
java.lang.IllegalStateException: Flow invariant is violated:
Emission from another coroutine is detected.
Child of StandaloneCoroutine{Active}@4903a45, expected child of StandaloneCoroutine{Completed}@988059a.
FlowCollector is not thread-safe and concurrent emissions are prohibited.
To mitigate this restriction please use 'channelFlow' builder instead of 'flow'
我使用send()时的错误
FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: pl.rybson.musicquiz, PID: 27105
kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed
最佳答案
当代码块运行完成时,流程
结束。
您可以使用 integration 而不是使用回调使其成为暂停功能。
fun registerFlow(email: String, password: String) = flow {
emit(AuthState.Loading)
val result = firebaseAuth.createUserWithEmailAndPassword(email, password).await()
if (result.isSuccessful) {
emit(AuthState.Success(result.result?.user))
} else {
emit(AuthState.Error(result.exception))
}
}
关于android - 从 Firebase 监听器发出状态 - Kotlin Flow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63990878/