kotlin flow 不从不同的函数发出值

kotlin flow is not emitting values from different function

我正在尝试实现 kotlin stateflow,但不知道它不起作用的原因。

当前输出: 验证 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"
}

}

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

您必须启动一个新协程来调用 collect,因为协程将继续收集值,直到其作业被取消。不要为此使用 runBlocking 构建器,而是使用 launch 构建器:

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

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

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

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

verificatio 34567
verificatio failed