Skip to content

Commit

Permalink
GlobalScope example
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperancinha committed Mar 17, 2024
1 parent c03ae22 commit de29809
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.jesperancinha.ktd

import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.time.delay
import kotlin.time.Duration.Companion.seconds
import kotlin.time.toJavaDuration

class GlobalScopeCoroutine {
companion object {
@OptIn(DelicateCoroutinesApi::class)
@JvmStatic
fun main(args: Array<String> = emptyArray()) {
val job = GlobalScope.launch {
delay(1.seconds.toJavaDuration())
}
println("Global >> Is the Global job cancelled? ${job.isCancelled}")
println("Global >> Is the Global job active? ${job.isActive}")
println("Global >> Is the Global job completed? ${job.isCompleted}")
job.cancel()
println("Global >> Is the Global job cancelled after cancel? ${job.isCancelled}")
runBlocking {
val jobInScope = launch {
delay(1.seconds.toJavaDuration())

}
jobInScope.cancel()
println("First Job >> Is this job cancelled? ${jobInScope.isCancelled}")
}
val lastJob = runBlocking {
val jobInScope = launch {
delay(1.seconds.toJavaDuration())

}
println("Second Job >> Is this job cancelled? ${jobInScope.isCancelled}")
println("Second Job >> Is this job active? ${jobInScope.isActive}")
println("Second Job >> Is this job completed? ${jobInScope.isCompleted}")
jobInScope
}
println("Second Job After Life-Cycle >> Is this job cancelled? ${lastJob.isCancelled}")
println("Second Job After Life-Cycle >> Is this job active? ${lastJob.isActive}")
println("Second Job After Life-Cycle >> Is this job completed? ${lastJob.isCompleted}")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ object Main {
RunningFold.main()
TicketCollectors.main()
SimpleConcurrency.main()
GlobalScopeCoroutine.main()
}
}

0 comments on commit de29809

Please sign in to comment.