【问题标题】:Suspending a Kotlin coroutine until a flow has a specific value暂停 Kotlin 协程,直到流具有特定值
【发布时间】:2020-11-23 14:02:08
【问题描述】:

我目前正在玩 Kotlin 协程和流程。在我的场景中,MutableStateFlow 表示连接状态 (CONNECTING, CONNECTED, CLOSING, CLOSED)。也可以登录、注销、重新登录。

为了进一步使用连接,我必须检查状态并等待它是CONNECTED。如果已经是CONNECTED,我可以继续。如果没有,我必须等到状态达到CONNECTEDconnect() 调用会立即返回,结果通过更新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

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

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

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

    最好使用first() 挂起直到匹配到谓词。

    if (connectionState.value != State.CONNECTED) {
        connectionState.first { it == State.CONNECTED }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多