5

这是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
}

+对表达感到困惑coroutineContext + job

它在做什么?是运算符覆盖吗?

4

1 回答 1

5

这是运算符重载的一个例子。下面显示了方法的文档CoroutineContext::plus

open operator fun plus(context: CoroutineContext): CoroutineContext

返回包含来自此上下文的元素和来自其他上下文的元素的上下文。删除此上下文中与另一个上下文中具有相同键的元素。

它基本上是两个上下文的合并。

于 2017-11-29T21:33:11.873 回答