【问题标题】:"+" in Kotlin Coroutines?Kotlin协程中的“+”?
【发布时间】:2018-05-13 16:25:06
【问题描述】:

这是 Kotlin Coroutines 的 Cancellation via explicit job 的示例代码:

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 感到困惑?

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

【问题讨论】:

标签: kotlin operator-overloading coroutine kotlinx.coroutines


【解决方案1】:

这是operator overloading 的一个例子。 下面是方法CoroutineContext::plus的文档:

open operator fun plus(context: CoroutineContext): CoroutineContext

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

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

【讨论】:

  • 这里值得注意的是,您始终可以通过 Ctrl+Click(在 Mac 上为 Cmd+Click)在 IDEA 代码中的 + 符号上导航到相应的方法以查看其文档。
  • launch(coroutineContext + job) {}launch(coroutineContext.plus(job) {} 相同,是缩写形式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2020-03-13
相关资源
最近更新 更多