import kotlinx.coroutines.*
droop enjoyable launchTask(delayMillis: Lengthy) {
println("START activity $delayMillis")
delay(delayMillis)
println("END launchTask $delayMillis")
}
enjoyable most important() = runBlocking {
println("begin most important")
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
launchTask(10000)
}
scope.launch {
launchTask(500)
}
// Cancel all coroutines within the scope after 2 seconds
delay(2000)
scope.cancel()
println("finish most important")
}
Right here we explicitly create a CoroutineScope
and use it to launch our two suspended operate calls, once more utilizing the default dispatcher. With the deal with to the scope, we are able to begin our jobs after which cancel them with scope.cancel()
. Discover that we now have two duties, one with a delay of 10,000 milliseconds. As a result of we cancel after 2,000 milliseconds, we get the next output:
begin most important
START activity 500
START activity 10000
END launchTask 500
finish most important
So, the ten,000-millisecond activity was began however by no means accomplished. As a substitute, it was canceled together with its enclosing scope.
For one more diploma of sophistication, we are able to add a withTimeout
block: