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

标签 android kotlin kotlin-coroutines

我想使用 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/

相关文章:

android - 取消广播接收器中的协程

android - 在android中更改方向时如何在onSaveInstanceState中保存Spinner的状态

android - 撰写 LazyList 部分背景

java - 循环 AsyncTask 类并获取 Json 并将其作为对象存储在列表中

java - 将 Kotlin 类转换为 Java

Android:在 attachBaseContext 中使用 DataStore

android - 任务 ':app:desugarDebugFileDependencies' 执行失败

android - 是否可以在android的新导航组件中发送字符串或整数以外的参数

gradle - 找不到ID为 `kotlin`的插件

kotlin - Kotlin协程:暂停后续访问 token 续订请求