【发布时间】:2019-05-20 15:08:02
【问题描述】:
如何从挂起函数启动协程并让它使用当前作用域? (这样 Scope 在启动的协程也结束之前不会结束)
我想写一些类似下面的东西——
import kotlinx.coroutines.*
fun main() = runBlocking { // this: CoroutineScope
go()
}
suspend fun go() {
launch {
println("go!")
}
}
但这有一个语法错误:“未解决的参考:启动”。看来launch 必须以下列方式之一运行——
GlobalScope.launch {
println("Go!")
}
或者
runBlocking {
launch {
println("Go!")
}
}
或者
withContext(Dispatchers.Default) {
launch {
println("Go!")
}
}
或者
coroutineScope {
launch {
println("Go!")
}
}
这些替代方案都不能满足我的需要。代码“阻塞”而不是“生成”,或者它生成但父作用域不会在父作用域本身结束之前等待其完成。
我需要它在当前父协程作用域中“生成”(启动),并且该父作用域应该等待生成的协程完成后再结束。
我预计suspend fun 中的简单launch 将有效并使用其父范围。
我正在使用Kotlin 1.3 和cotlinx-coroutines-core:1.0.1。
【问题讨论】: