Skip to content

Instantly share code, notes, and snippets.

@neogeogre
Created October 18, 2023 09:52
Show Gist options
  • Save neogeogre/6e6f857dbb5d16fe75968b4a311aa5c4 to your computer and use it in GitHub Desktop.
Save neogeogre/6e6f857dbb5d16fe75968b4a311aa5c4 to your computer and use it in GitHub Desktop.
trigger and stop multiple // jobs with kotlin coroutine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun main() {
val jobs = List(5) {
val job = CoroutineScope(Dispatchers.Default).launch {
delay(2000)
println("Work $it is done")
}
CoroutineScope(Dispatchers.Default).launch {
job.join()
println("join isActive ${job.isActive} isCancelled ${job.isCancelled} isCompleted ${job.isCompleted}")
}
job
}
println("Jobs are running...")
jobs.forEach {
CoroutineScope(Dispatchers.Default).launch {
it.cancel()
println("cancelAndJoin isActive ${it.isActive} isCancelled ${it.isCancelled} isCompleted ${it.isCompleted}")
}
}
Thread.sleep(5000)
println("over")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment