Last active
May 2, 2021 22:16
-
-
Save rashanjyot/5469939fc22dd36b21e073706638cf75 to your computer and use it in GitHub Desktop.
Structured Concurrency (Example 2)
This file contains 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 parentJob = launch { | |
val childJob = launch { | |
var count = 1 | |
val startTime = System.currentTimeMillis() | |
var nextPrintTime = startTime | |
while (count <= 5) { | |
if (System.currentTimeMillis() >= nextPrintTime) { | |
println("Count: $count") | |
nextPrintTime += 100L | |
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 // cancels parentJob and hence, cancels childJob recursively | |
Count: 4 // childJob continues executing its code | |
Count: 5 | |
Parent job completed // parentJob completes only after childJob. (Structured Concurrency) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment