“+” in Kotlin Coroutines?

我的梦境 提交于 2020-05-08 04:11:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/47561627/in-kotlin-coroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!