【发布时间】:2020-07-15 11:26:29
【问题描述】:
CoroutineScope(dispatchers).launch{} 和 coroutineScope{ launch{}} 有什么区别?
假设我有以下代码:
(你可以去 Kotlin Playground 运行这个 sn-p https://pl.kotl.in/U4eDY4uJt)
suspend fun perform(invokeAfterDelay: suspend () -> Unit) {
// not printing
CoroutineScope(Dispatchers.Default).launch {
delay(1000)
invokeAfterDelay()
}
// will print
coroutineScope {
launch {
delay(1000)
invokeAfterDelay()
}
}
}
fun printSomething() {
println("Counter")
}
fun main() {
runBlocking {
perform {
printSomething()
}
}
}
正如评论所述,当使用CoroutineScope().launch 时,它不会调用打印,但是当使用其他方式时,代码会按预期运行。
有什么区别?
谢谢。
其他问题
新发现。
如果我像这样离开perform 函数(不注释掉协程之一)
suspend fun perform(invokeAfterDelay: suspend () -> Unit) {
CoroutineScope(Dispatchers.Default).launch {
delay(1000)
invokeAfterDelay()
}
coroutineScope {
launch {
delay(1000)
invokeAfterDelay()
}
}
}
那么这两个协程都会被执行??????为什么?
【问题讨论】:
-
请阅读这个问题和答案,进一步解释:stackoverflow.com/questions/59368838/…
标签: kotlin kotlin-coroutines coroutinescope