CodexBloom - Programming Q&A Platform

Kotlin Coroutines: Issues with Cancellation Not Propagating in a Nested Coroutine Structure

👀 Views: 20 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
kotlin coroutines cancellation

I'm facing an issue with Kotlin coroutines where cancellation is not propagating correctly through a nested coroutine structure. I have a parent coroutine that launches a child coroutine, but when I attempt to cancel the parent, the child coroutine continues executing. Here's a simplified version of my code: ```kotlin import kotlinx.coroutines.* class Example { private val scope = CoroutineScope(Dispatchers.Main) fun startProcess() { scope.launch { val job = launch { // Simulating a long-running task try { repeat(5) { i -> delay(1000) println("Child Coroutine: $i") } } catch (e: CancellationException) { println("Child Coroutine was cancelled") } } // Simulating some other work in the parent delay(2000) println("Cancelling Parent Coroutine") job.cancel() // This cancels the child coroutine } } } fun main() { val example = Example() example.startProcess() Thread.sleep(3000) // Wait for the parent coroutine to execute } ``` When I run this code, I see that the "Child Coroutine: 0" and "Child Coroutine: 1" logs appear even after the cancellation is initiated. I expected the child coroutine to stop executing after calling `job.cancel()`. I've tried wrapping the `repeat` loop in a `try-catch` block to catch any `CancellationException`, but it seems to make no difference. What am I missing here? Is there a best practice for ensuring cancellation propagates correctly in nested coroutines? I'm using Kotlin 1.5.31 and coroutines 1.5.2. I'm working with Kotlin in a Docker container on Linux. Am I approaching this the right way? This is my first time working with Kotlin LTS. Am I approaching this the right way?