natario1
04/29/2021, 4:09 PMclass Worker {
fun doWork()
fun cancelWork()
}
My attempt below (untested) doesn't look very good, I wonder if there's any better way.
coroutineScope {
val job = launch {
while (isActive) {
delay(50)
}
}
job.invokeOnCompletion {
if (it is CancellationException) {
worker.cancelWork()
}
}
worker.doWork()
job.cancel()
}
araqnid
04/30/2021, 9:08 AMlaunch{}
as coroutineContext[Job]
which would probably read better. I think with that there’s no need for the explicit cancel, just sth like:
launch {
coroutineContext[Job]!!.invokeOnCompletion {
if (it is CancellationException) {
worker.cancelWork()
}
}
worker.doWork()
}
I also think that means there’s no need for the outer scope coroutine which is only there to cancel the inner one.natario1
04/30/2021, 10:07 AMnatario1
04/30/2021, 10:22 AM