Kotlin协程中的“+”?
这是通过 Kotlin Coroutines的显式工作取消示例代码:
fun main(args: Array) = runBlocking { 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 }
我很困惑+
expression式coroutineContext + job
?
它在做什么? 是操作员覆盖?
这是运算符重载的一个例子。 以下显示方法CoroutineContext::plus
的文档:
open operator fun plus(context: CoroutineContext): CoroutineContext
返回包含此上下文元素和其他上下文元素的上下文。 这个上下文中的元素和另一个中的元素是一样的。
这基本上是两个上下文的合并。