Skip to content

Instantly share code, notes, and snippets.

@rashanjyot
Last active May 2, 2021 22:16
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/5469939fc22dd36b21e073706638cf75 to your computer and use it in GitHub Desktop.
Save rashanjyot/5469939fc22dd36b21e073706638cf75 to your computer and use it in GitHub Desktop.
Structured Concurrency (Example 2)
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