Android 暂停Kotlin协程,直到流具有特定值
我目前正在与Kotlin合作项目和流程。在我的场景中,Android 暂停Kotlin协程,直到流具有特定值,android,kotlin,kotlin-coroutines,kotlin-coroutines-flow,Android,Kotlin,Kotlin Coroutines,Kotlin Coroutines Flow,我目前正在与Kotlin合作项目和流程。在我的场景中,MutableStateFlow表示连接状态(CONNECTING,CONNECTED,CLOSING,CLOSED)。还可以登录、注销和再次登录 为了进一步使用连接,我必须检查状态并等待它连接到。如果它已连接,我可以继续。如果没有,我必须等待状态达到连接状态。connect()调用确实会立即返回,结果通过更新MutableStateFlow的回调进行传播。我目前的想法是做以下工作: connect() if (connectionStat
MutableStateFlow
表示连接状态(CONNECTING,CONNECTED,CLOSING,CLOSED
)。还可以登录、注销和再次登录
为了进一步使用连接,我必须检查状态并等待它连接到
。如果它已连接,我可以继续。如果没有,我必须等待状态达到连接状态。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
connect()
如果(connectionState.value!=State.CONNECTED){//connectionState=MutableStateFlow(State.CLOSED)
suspendCoroutine{continuation->
scope.launch{//scope=MainScope()
connectionState.collect{
if(it==State.CONNECTED){
继续。继续(正确)
}
}
}
}
}
//继续
由于我对这个话题还比较陌生,我不知道这是否是一个好的实践,我也无法在Kotlin文档中找到一个更合适的概念。有更好的方法吗?不久前我也有同样的问题: 最好使用
first()
暂停,直到匹配谓词
if(connectionState.value!=State.CONNECTED){
connectionState.first{it==State.CONNECTED}
}