Hey I have a question on `async` and cancellations...
# coroutines
p
Hey I have a question on
async
and cancellations. Lets say I have:
Copy code
withContext(dispatcher) {
    val job = async { while(true) { delay(150) } }
    withTimeoutOrNull(200) { job.await() }
}
Id think this would start some async job, and then wait for its completion for 200ms. If the job takes longer than 200ms, it cancels the await and the async job. Right now it looks like nothing times out. Am I missing something?
d
Only
{ job.await() }
gets cancelled in this case, that is, the process of waiting for the
job
to complete. Nothing cancels the
job
itself. Related issue: https://github.com/Kotlin/kotlinx.coroutines/issues/4329
p
Thanks for the quick response. Would it be okay to than cancel the
job
myself on receiving null from the
withTimeoutOrNull
. Or would there be a better/cleaner way of achieving what I want?
d
Or would there be a better/cleaner way of achieving what I want?
This depends entirely on what you want! How about this?
Copy code
withContext(dispatcher) {
    val job = async {
        withTimeoutOrNull(200) {
            while(true) { delay(150) }
        }
    }
    job.await()
}
p
Ahh smart, I did not think of this solution. Thanks a lot, I’ll give it a try!
u
In your example, there is no need for async at all. If this is not only an artefact of creating a minimalist example, you can just drop async completely:
Copy code
withTimeoutOrNull(200) {
    withContext(dispatcher) {
        while(true) { delay(150) }
    }
}
👍 1