Kotlin 协程中的“+”?
"+" in Kotlin Coroutines?
这是 Cancellation via explicit job Kotlin 协程的示例代码:
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
?
中的 +
感到困惑
它在做什么?是不是运算符覆盖?
这是operator overloading的一个例子。
下面是方法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.
它基本上是两个上下文的合并。
这是 Cancellation via explicit job Kotlin 协程的示例代码:
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
?
+
感到困惑
它在做什么?是不是运算符覆盖?
这是operator overloading的一个例子。
下面是方法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.
它基本上是两个上下文的合并。