Cancel chain of coroutines


#1

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?


#2

See here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#cancellation-is-cooperative

You can fix this example code using yield https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html


#3

@fvasco Thanks, yes it’s the same.