# Cancel chain of coroutines

**URL:** <https://discuss.kotlinlang.org/t/cancel-chain-of-coroutines/9543>\
**Category:** Support\
**Created:** [September 24, 2018, 12:15pm UTC](https://discuss.kotlinlang.org/t/cancel-chain-of-coroutines/9543 "2018-09-24T12:15:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexandr.zhitlukhin](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@alexandr.zhitlukhin](https://discuss.kotlinlang.org/u/alexandr.zhitlukhin)\
**Post date:** [September 24, 2018, 12:15pm UTC](https://discuss.kotlinlang.org/t/cancel-chain-of-coroutines/9543/1 "2018-09-24T12:15:06Z")

</div>

How i can synchronously cancel coroutine with inner coroutine?  
Here is an example:

```auto
@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:

```auto
1
2
3
Coroutine canceled
4
5
Job was canceled
Work is done

```

Can i stop calculation after 3 iterations?

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [September 24, 2018, 12:30pm UTC](https://discuss.kotlinlang.org/t/cancel-chain-of-coroutines/9543/2 "2018-09-24T12:30:43Z")

</div>

See here: [kotlinx.coroutines/coroutines-guide.md at master · Kotlin/kotlinx.coroutines · GitHub](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](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html)

---

<div class="post-metadata">

**Author:** ![alexandr.zhitlukhin](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@alexandr.zhitlukhin](https://discuss.kotlinlang.org/u/alexandr.zhitlukhin)\
**Post date:** [September 24, 2018, 12:39pm UTC](https://discuss.kotlinlang.org/t/cancel-chain-of-coroutines/9543/3 "2018-09-24T12:39:30Z")

</div>

@fvasco Thanks, yes it’s the same.
