暂停协程,直到条件成立

时间:2018-12-23 18:40:04

标签: kotlin kotlin-coroutines

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

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()
    }
}

我想使用Kotlin Coroutines为该Service类(我不控制)编写包装。 这是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()行为?预先感谢。

4 个答案:

答案 0 :(得分:2)

这是实现它的方法:

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()

    ...
}

一般说明:仅仅因为该服务在某个时间点已连接并不能保证在您使用该服务时它仍然可以连接。

答案 1 :(得分:0)

您处于暂停状态,为什么不喜欢这样的东西?

while (!service.isConnected()) {
    delay(1000)
}

您可以在此语句中添加其他超时条件。

答案 2 :(得分:0)

  1. suspendCoroutine暂停当前正在运行的协程,因此无需预先暂停。

在暂停函数中获取当前的延续实例,并暂停当前正在运行的协程。

  1. 换句话说,我建议使用async并返回一个DeferredServiceWrapper的挂起实际上不是工作。调用方应控制何时需要结果,并在需要时暂停。
class ServiceWrapper {

    ...

    fun performAction(actionName: String): Deferred<ActionResult> = coroutineScope.async {
        suspendCoroutine { continuation ->
            service.performAction(actionName, object : ActionCallback() {
                override fun onSuccess(result: ActionResult) {
                    continuation.resume(result)
                }

                override fun onError() {
                    continuation.resumeWithException(RuntimeException())
                }
            }
        }
    }
}
  1. 如果出于某种原因您必须在suspendCoroutine之前暂停,我建议您使用CompletableJobDeferred应该返回结果。在我看来,使用Deferred<Unit>似乎是一种反模式。

答案 3 :(得分:0)

另一种使用 StateFlow

的方法
  1. 先定义一些“状态”
enum class ServiceState {
    CONNECTED, SUSPENDED, FAILED
}
  1. 将基于回调的代码转换为流
val connectionState = MutableStateFlow(ServiceState.FAILED)

private val service = Service(object : ConnectionCallback {
    override fun onConnected() {
        connectionState.value = ServiceState.CONNECTED
    }

    override fun onConnectionSuspended() {
        connectionState.value = ServiceState.SUSPENDED
    }

    override fun onConnectionFailed() {
        connectionState.value = ServiceState.FAILED
    }
})
  1. 复制并粘贴这些实用程序代码
class ConditionalAwait<T>(
    private val stateFlow: StateFlow<T>,
    private val condition: (T) -> Boolean
) {
    suspend fun await(): T {
        val nowValue = stateFlow.value
        return if (condition(nowValue)) {
            nowValue
        } else {
            stateFlow.first { condition(it) }
        }
    }
}

suspend fun <T> StateFlow<T>.conditionalAwait(condition: (T) -> Boolean): T =
    ConditionalAwait(this, condition).await()
  1. 使用它~
suspend fun performActionWhenConnected() {
    connectionState.conditionalAwait { it == ServiceState.CONNECTED }
    // other actions when service is connected
}

  1. 高级用法
suspend fun performActionWhenConnected() {
    val state = connectionState.conditionalAwait { 
        it == ServiceState.CONNECTED || it == ServiceState.FAILED
    } // keep suspended when Service.SUSPENDED

    if (state is ServiceState.CONNECTED) {
        // other actions when service is connected
    } else {
        // error handling
    }
}