【发布时间】:2020-11-23 14:02:08
【问题描述】:
我目前正在玩 Kotlin 协程和流程。在我的场景中,MutableStateFlow 表示连接状态 (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
由于我对这个主题还很陌生,我不知道这是否是一种好的做法,而且我也无法在 Kotlin 文档中找到更合适的概念。有没有更好的方法?
【问题讨论】:
标签: android kotlin kotlin-coroutines