Skip to content

Instantly share code, notes, and snippets.

@rashanjyot
Last active May 3, 2021 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rashanjyot/66aca4c8ca50d8043df5caeb05e84fa5 to your computer and use it in GitHub Desktop.
Save rashanjyot/66aca4c8ca50d8043df5caeb05e84fa5 to your computer and use it in GitHub Desktop.
Structured Concurrency (Example 3)
val parallelJob = launch {
delay(1000)
}
val parentJob = launch {
val childJob = launch(parallelJob) { // Notice how the context is explicitly provided
var count = 1
while (count <= 5) {
println("Count: $count")
delay(100)
count++
}
}
}
delay(250)
println("Cancelling parent job")
parentJob.cancel()
parentJob.join()
println("Parent job completed")
-----------
OUTPUT:
Count: 1
Count: 2
Count: 3
Cancelling parent job
Parent job completed
Count: 4
Count: 5 // childJob continues after parentJob (CoroutineScope),
// and is bound to parallelJob (CoroutineContext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment