【发布时间】:2020-09-21 10:56:13
【问题描述】:
我想使用 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
【问题讨论】:
标签: android kotlin kotlin-coroutines