gpt4 book ai didi

android - 从 Firebase 监听器发出状态 - Kotlin Flow

转载 作者:行者123 更新时间:2023-12-04 14:44:43 25 4
gpt4 key购买 nike

我想使用 Kotlin Flow 来处理 FirebaseAuth 状态。我知道下面的代码是错误的,但我不知道如何修复它。我尝试使用 channelFlow 并且当我想要 sendoffer

时它总是崩溃
   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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com