import kotlinx.coroutines.*
suspend fun launchTask(delayMillis: Long) {
println(“START task $delayMillis”)
delay(delayMillis)
println(“END launchTask $delayMillis”)
}
fun main() = runBlocking {
println(“start main”)
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
launchTask(10000)
}
scope.launch {
launchTask(500)
}
// Cancel all coroutines in the scope after 2 seconds
delay(2000)
scope.cancel()
println(“end main”)
}
Here we explicitly create a CoroutineScope and use it to launch our two suspended function calls, again using the default dispatcher. With the handle to the scope, we can start our jobs and then cancel them with scope.cancel(). Notice that we have two tasks, one with a delay of 10,000 milliseconds. Because we cancel after 2,000 milliseconds, we get the following output:
start main
START task 500
START task 10000
END launchTask 500
end main
So, the 10,000-millisecond task was started but never completed. Instead, it was canceled along with its enclosing scope.
For another degree of sophistication, we can add a withTimeout block: