3

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

4

1 回答 1

3

您必须启动一个新的协程来调用collect,因为协程将继续收集值,直到其 Job 被取消。不要runBlocking为此使用launchbuilder ,而是使用 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
于 2020-06-11T11:26:39.727 回答