coroutineScope 不等待子协程?

问题描述 投票:0回答:1

我尝试学习 Kotlin 中的协程,现在我在 Kotlin Playground 中使用的一些代码遇到了问题。

我有两个挂起功能。一个延迟3秒。我将在协程范围内调用这两个函数。如果我在主函数中调用 getWeatherReport() ,我希望它几乎同时打印两条消息,因为它说,协程作用域等待其所有子协程完成计算,然后返回。 但为什么这里 30 Degrees 在 100 ms 后立即打印出来?

来自官方文档:“一旦给定的块及其所有子协程完成,该函数就会返回。” 函数返回到底意味着什么?

suspend fun getWeatherReport() = coroutineScope {


launch { getTemperature() }
launch { getWind() }

}


suspend fun getTemperature(){
delay(100)
println("30 Degrees")
}

suspend fun getWind(){
delay(3000)
println("Wind by North")
}
android kotlin asynchronous scope kotlin-coroutines
1个回答
0
投票

您正在创建两个独立的协程。

将两个挂起函数放在同一个启动中,它们将相互等待。

coroutineScope.launch { 
    getTemperature() 
    getWind()
}
© www.soinside.com 2019 - 2024. All rights reserved.