https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dominaezzz

07/15/2018, 5:59 PM
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

elizarov

07/15/2018, 6:47 PM
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
        }
    }
}
214 Views