首页 > 解决方案 > 协程作用域构建器流程如何工作

问题描述

科特林 说

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和的理解coroutineScope。这没有按预期工作。

输出是

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

任何人都可以以一种简单的方式解释这一点。

标签: kotlinkotlin-coroutines

解决方案


launch导致块异步执行,因此调用launch立即返回,协程继续运行,不等待启动块的执行。

因此,紧接在runBlocking被调用之后,第一个和第二个launch被一个接一个地调用,并且紧接着协程被挂起delay(100L)

100 毫秒后,协程恢复并打印“来自协程范围的任务”,然后嵌套协程范围的块的执行结束。协程作用域总是等待它启动的所有作业的执行结束,所以它在这里等待 500 毫秒。

同时执行了两个已启动的块,因此首先打印“Task from runBlocking”(距开始 200 毫秒后),然后打印“来自嵌套启动的任务”(距开始 500 毫秒后)。

最终,在内部启动的作业完成后,内部协程范围完成等待,外部协程继续并打印“协程范围结束”。

这就是故事。我希望它有助于理解代码是如何执行的,以及为什么打印的顺序是这样的。


推荐阅读