Hi, I'm trying to transform a callback-based function to a coroutine. Here's what I have so far
suspend fun fastSubscribe(path: String): Value =
suspendCancellableCoroutine { cont: CancellableContinuation<Value> ->
val handler = object : Handler<SubscriptionValue> {
override fun handle(event: SubscriptionValue) {
requester.unsubscribe(path, this)
cont.resume(event.value)
}
}
requester.subscribe(path, handler)
}
Here I want to finish the execution with the value in the callback when I have one, but I'd like to add a timeout for if I never get a value (ie: when
handle
is never called)
I think I should use a
withTimeout
in there but I don't know where exactly. On timeout I need to call
requester.unsubscribe(handler)
, so having the
withTimeout
on the call site of
fastSubscribe
isn't really a solution. Is there anything I can do with this?