How i can synchronously cancel coroutine with inner coroutine?
Here is an example:
@Test
fun cancelCoroutine() {
runBlocking {
try {
val warpper = async {
val ctx = kotlin.coroutines.experimental.coroutineContext
val runnable = java.lang.Runnable {
ctx.cancel()
println("Coroutine canceled")
}
val deferredCalculations = async {
for (i in 1..5) {
println("$i")
if (i == 3) {
runnable.run()
}
}
}
deferredCalculations.await()
}
warpper.await()
} catch (e: CancellationException) {
println("Job was canceled")
} finally {
println("Work is done")
}
}
}
And in the log:
1
2
3
Coroutine canceled
4
5
Job was canceled
Work is done
Can i stop calculation after 3 iterations?