How can I launch a coroutine from a suspend function and have it use the current Scope? (so that the Scope doesn't end until the launched coroutine also ends)
我想写下如下内容——
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!")
}
}
这些 Select 都不能满足我的需要.要么代码"阻塞"而不是"繁殖",要么它繁殖,但父作用域不会在父作用域本身结束之前等待其完成.
I need it to "spawn" (launch) in the current parent coroutine scope, and that parent scope should wait for the spawned coroutine to finish before it ends itself.
我希望suspend fun
中的简单launch
是有效的,并使用其父范围.
I'm using Kotlin 1.3
and cotlinx-coroutines-core:1.0.1
.