Kotlin流没有从其他函数中发出值

时间:2020-06-11 10:50:58

标签: kotlin-coroutines kotlin-flow kotlin-coroutines-flow

我正在尝试实现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"
}

}

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

1 个答案:

答案 0 :(得分:2)

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

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