【问题标题】:kotlin flow is not emitting values from different functionkotlin flow 没有从不同的函数发出值
【发布时间】:2020-09-30 23:55:52
【问题描述】:

我正在尝试实现 kotlin 状态流,但无法知道它不起作用的原因。

电流输出: 验证34567

预期输出: 验证 34567 验证失败

package stateflowDuplicate

import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
val firebasePhoneVerificationListener = FirebaseOTPVerificationOperation1()
val oTPVerificationViewModal = OTPVerificationViewModal1(firebasePhoneVerificationListener)
oTPVerificationViewModal.fail()
}

class OTPVerificationViewModal1(private val firebasePhoneVerificationListener: FirebaseOTPVerificationOperation1) {

init {
    startPhoneNumberVerification()
    setUpListener()
}

 suspend fun fail(){
    firebasePhoneVerificationListener.fail()
}

private fun startPhoneNumberVerification() {
    firebasePhoneVerificationListener.initiatePhoneVerification("34567")
}

private fun setUpListener() {
    runBlocking {
        firebasePhoneVerificationListener.phoneVerificationFailed.collect {
            println("verificatio $it")
        }
    }
}

}

Second class
package stateflowDuplicate

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.runBlocking

class FirebaseOTPVerificationOperation1 {

private val _phoneVerificationFailed = MutableStateFlow<String?>(null)
val phoneVerificationFailed: StateFlow<String?>
    get() = _phoneVerificationFailed

  fun initiatePhoneVerification(phoneNumber: String) {
         _phoneVerificationFailed.value = phoneNumber
}
 suspend fun fail() {
     delay(200L)
    _phoneVerificationFailed.value = "failed"
}

}

试图从这些链接中理解这个概念, Link1 Link2

【问题讨论】:

    标签: kotlin-flow kotlin-coroutines


    【解决方案1】:

    你必须启动一个新的协程来调用collect,因为协程会一直收集值直到它的 Job 被取消。不要为此使用runBlocking builder,而是使用launch builder:

    private fun setUpListener() = launch {
        firebasePhoneVerificationListener.phoneVerificationFailed.collect {
            println("verificatio $it")
        }
    }
    

    现在要让它工作,你需要在你的类中实现CoroutineScope 接口。你可以这样做:

    class OTPVerificationViewModal1(
        private val firebasePhoneVerificationListener: FirebaseOTPVerificationOperation1
    ): CoroutineScope by CoroutineScope(Dispatchers.Default) {
        ...
    }
    

    如果你现在运行它,你会得到这个输出:

    verificatio 34567
    verificatio failed
    

    【讨论】:

    • 感谢您的快速响应,但您能告诉我为什么它不能与 viewmodal 一起使用,因为 coroutinescope 默认存在于 ktx 中
    • 请查看此链接,stackoverflow.com/questions/62331931/…,问题是一样的,但它与 viewmodal android 相关
    • 请帮我解决上面链接的问题,因为我已经按照这里的当前答案做了所有事情,但仍然没有触发
    • @Reprator 我看到了您的代码,但很难跟踪,因为有些部分不清楚它们的作用。我会使用日志来查看是否正在调用每个方法。比如secondCall方法里面,resendPhoneVerificationCode方法里面等等。
    • 请再看一遍这个问题,我已经用最少的代码更新了这个问题,以及当前和预期的输出
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2022-09-27
    • 2023-01-31
    • 2021-10-28
    • 2021-02-13
    相关资源
    最近更新 更多