Created
October 18, 2023 09:52
-
-
Save neogeogre/6e6f857dbb5d16fe75968b4a311aa5c4 to your computer and use it in GitHub Desktop.
trigger and stop multiple // jobs with kotlin coroutine
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
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