This is example code for a Cancellation via explicit job for Kotlin Coroutines:
fun main(args: Array<String>) = runBlocking<Unit> {
val job = Job() // create a job object to manage our lifecycle
// now launch ten coroutines for a demo, each working for a different time
val coroutines = List(10) { i ->
// they are all children of our job object
launch(coroutineContext + job) { // we use the context of main runBlocking thread, but with our own job object
delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc
println("Coroutine $i is done")
}
}
println("Launched ${coroutines.size} coroutines")
delay(500L) // delay for half a second
println("Cancelling the job!")
job.cancelAndJoin() // cancel all our coroutines and wait for all of them to complete
}
I am confused about +
in the expression coroutineContext + job
?
What it is doing? Is it operator overwriting?
It’s an example of operator overloading.
The following shows the documentation of method CoroutineContext::plus
:
open operator fun plus(context: CoroutineContext): CoroutineContext
Returns a context containing elements from this context and elements from other context. The elements from this context with the same key as in the other one are dropped.
It’s basically a merge of two contexts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With