Cancel chain of coroutines

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?

See here: kotlinx.coroutines/coroutines-guide.md at master · Kotlin/kotlinx.coroutines · GitHub

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

1 Like

@fvasco Thanks, yes it’s the same.