[英]Suspending a Kotlin coroutine until a flow has a specific value
我目前正在使用 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 文档中找到更合适的概念。 有没有更好的方法来做到这一点?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.