我有一个用例,我需要与充当服务的类建立连接和断开连接。仅在连接服务后才能对服务执行操作。服务通过回调连接或断开时会通知客户端:
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()
行为?预先感谢。
答案 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)
suspendCoroutine
暂停当前正在运行的协程,因此无需预先暂停。在暂停函数中获取当前的延续实例,并暂停当前正在运行的协程。
async
并返回一个Deferred
。 ServiceWrapper
的挂起实际上不是工作。调用方应控制何时需要结果,并在需要时暂停。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())
}
}
}
}
}
suspendCoroutine
之前暂停,我建议您使用CompletableJob
。 Deferred
应该返回结果。在我看来,使用Deferred<Unit>
似乎是一种反模式。答案 3 :(得分:0)
另一种使用 StateFlow
enum class ServiceState {
CONNECTED, SUSPENDED, FAILED
}
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
}
})
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()
suspend fun performActionWhenConnected() {
connectionState.conditionalAwait { it == ServiceState.CONNECTED }
// other actions when service is connected
}
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
}
}