Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"+" in Kotlin Coroutines?

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?

like image 738
user3239558 Avatar asked Nov 29 '17 20:11

user3239558


1 Answers

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.

like image 178
s1m0nw1 Avatar answered Sep 25 '22 20:09

s1m0nw1