暂停 Kotlin 协程,直到流具有特定值

LN-*_*-12 6 android kotlin kotlin-coroutines kotlin-coroutines-flow

我目前正在使用 Kotlin 协程和流程。在我的场景中, aMutableStateFlow代表连接状态 ( CONNECTING, CONNECTED, CLOSING, CLOSED)。也可以登录、注销和再次登录。

为了进一步使用连接,我必须检查状态并等到它是CONNECTED. 如果已经是CONNECTED,我可以继续。如果没有,我必须等到状态达到CONNECTED. 该connect()调用不会返回通过可更新回调马上,结果被传播MutableStateFlow。我目前的想法是做以下事情:

connect()

if (connectionState.value != State.CONNECTED) { // connectionState = MutableStateFlow(State.CLOSED)

    suspendCoroutine<Boolean> { continuation ->
        scope.launch { // scope = MainScope()
            connectionState.collect {
                if (it == State.CONNECTED) {
                    continuation.resume(true)
                }
            }
        }
    }
}

// continue
Run Code Online (Sandbox Code Playgroud)

由于我对这个主题还很陌生,我不知道这是否是一种好的做法,而且我也无法在 Kotlin 文档中找到更合适的概念。有没有更好的方法来做到这一点?

Ani*_*ahu 8

不久前,我有同样的问题:

在此处输入图片说明

最好使用first()暂停直到谓词匹配。

if (connectionState.value != State.CONNECTED) {
    connectionState.first { it == State.CONNECTED }
}
Run Code Online (Sandbox Code Playgroud)