Last active
May 3, 2021 06:55
-
-
Save rashanjyot/66aca4c8ca50d8043df5caeb05e84fa5 to your computer and use it in GitHub Desktop.
Structured Concurrency (Example 3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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