gpt4 book ai didi

kotlin - 暂停协程直到条件为真

转载 作者:行者123 更新时间:2023-12-02 12:25:01 24 4
gpt4 key购买 nike

我有一个用例,我需要连接和断开作为服务的类。只有在服务连接时才能对服务执行操作。当服务连接或断开时通过回调通知客户端:

class Service {

constructor(callback: ConnectionCallback) { ... }

fun connect() {
// Call callback.onConnected() some time after this method returns.
}

fun disconnect() {
// Call callback.onConnectionSuspended() some time after this method returns.
}

fun isConnected(): Boolean { ... }

fun performAction(actionName: String, callback: ActionCallback) {
// Perform a given action on the service, failing with a fatal exception if called when the service is not connected.
}

interface ConnectionCallback {
fun onConnected() // May be called multiple times
fun onConnectionSuspended() // May be called multiple times
fun onConnectionFailed()
}
}

我想为此编写一个包装器 Service类(我无法控制)使用 Kotlin 协程。
这是 ServiceWrapper的骨架:
class ServiceWrapper {
private val service = Service(object : ConnectionCallback { ... })

fun connect() {
service.connect()
}

fun disconnect() {
service.disconnect()
}

suspend fun performActionWhenConnected(actionName: String): ActionResult {
suspendUntilConnected()

return suspendCoroutine { continuation ->
service.performAction(actionName, object : ActionCallback() {
override fun onSuccess(result: ActionResult) {
continuation.resume(result)
}

override fun onError() {
continuation.resumeWithException(RuntimeException())
}
}
}
}
}

我该如何实现 suspendUntilConnected()使用协程的行为?提前致谢。

最佳答案

以下是您可以如何实现它:

class ServiceWrapper {
@Volatile
private var deferredUntilConnected = CompletableDeferred<Unit>()

private val service = Service(object : ConnectionCallback {
override fun onConnected() {
deferredUntilConnected.complete(Unit)
}

override fun onConnectionSuspended() {
deferredUntilConnected = CompletableDeferred()
}
})

private suspend fun suspendUntilConnected() = deferredUntilConnected.await()

...
}

一般注意事项:仅仅因为服务在某个时刻连接并不能保证在您使用它时它仍然会连接。

关于kotlin - 暂停协程直到条件为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com