【问题标题】:Console output awaits coroutineScope {} body completion控制台输出等待 coroutineScope {} 主体完成
【发布时间】:2021-03-18 22:23:55
【问题描述】:

有一个例子:

import kotlinx.coroutines.*
 
fun main() = runBlocking { // this: CoroutineScope
 
    launch {
        delay(200L)
        println("Task from runBlocking")
    }
 
    coroutineScope { // Creates a coroutine scope
        launch {
            delay(500L)
            println("Task from nested launch")
        }
 
        delay(100L)
        println("Task from coroutine scope") // This line will be printed before the nested launch
    }
 
    println("Coroutine scope is over") // This line is not printed until the nested launch completes
}

结果是这样的:

协程范围内的任务

来自 runBlocking 的任务

来自嵌套启动的任务

协程作用域结束

你能解释一下为什么第 20 行的输出 (println("Coroutine scope is over")) 出现在 coroutineScope{} 主体完成后的最后吗?

我只是想,第 20 行在 主线程 上运行,而 launch{}coroutineScope{} 创建的协程正在运行在平行下。所以我预料到了

协程作用域结束

在开头显示。

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案1】:

    从函数 coroutineScope 的文档中,它说它暂停并且在其所有子协程完成之前不会返回:

    一旦给定块及其所有子协程完成,此函数就会返回。

    如果您创建一个子作用域并在其上调用启动,则行为将与您预期的一样:

    fun main() = runBlocking {
    
        launch {
            delay(200L)
            println("Task from runBlocking")
        }
    
        val scope = CoroutineScope(coroutineContext)
        scope.launch {
            launch {
                delay(500L)
                println("Task from nested launch")
            }
    
            delay(100L)
            println("Task from coroutine scope")
        }
    
        println("Coroutine scope is over")
    }
    

    输出

    Coroutine scope is over
    Task from coroutine scope
    Task from runBlocking
    Task from nested launch
    

    【讨论】:

    • 为什么不写launch { ... } 而不是CoroutineScope(coroutineContext).launch { ... }
    • 只是显示CoroutineScope()coroutineScope的区别,因为OP似乎在探索如何创建一个独立的CoroutineScope。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多