Kotlin协程中的“ +”?

用户名

这是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吗?

它在做什么?是操作员覆盖吗?

s1m0nw1

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

open operator fun plus(context: CoroutineContext): CoroutineContext

返回一个上下文,其中包含该上下文中的元素和其他上下文中的元素。该上下文中与其他元素具有相同键的元素将被删除。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章