Is it possible to wrap an async api based on polli...
# coroutines
d
Is it possible to wrap an async api based on polling (instead of callbacks) in a suspend function(or coroutine)? ...without another thread of course. So only
makeRequest(): Request
,
Request.isDone(): Boolean
,
Request.cancel()
and
Request.getResult(): Result
are available.
e
Yes. You can suspend the coroutine that is waiting for result, while launching another coroutine to poll periodically and resume the suspended one.
Something like this:
Copy code
suspend fun Request.await(): Result = suspendCancellableCoroutine<Result> { cont ->
    launch(cont.context) {
        while (true) {
            if (isDone()) {
                cont.resume(getResult())
                break
            }
            delay(100) // poll interval
        }
    }
}
251 Views