use*_*558 5 operator-overloading coroutine kotlin kotlinx.coroutines
这是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
}
Run Code Online (Sandbox Code Playgroud)
我+对表达感到困惑coroutineContext + job?
它在做什么?它是运算符覆盖吗?
这是运算符重载的一个例子。以下显示了方法的文档CoroutineContext::plus:
open operator fun plus(context: CoroutineContext): CoroutineContext
Run Code Online (Sandbox Code Playgroud)
返回包含来自此上下文的元素和来自其他上下文的元素的上下文。删除此上下文中与另一个上下文中具有相同键的元素。
它基本上是两个上下文的合并。
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |