kotlin/coroutineScope()
from Kotlinのコルーチン
coroutineScope() は、起動したコルーチンを含むすべての処理が完了した場合にのみ返される。
内部の非同期実行処理をまとめて、外からは同期処理に見えるように包み込むことができる
code:kotlin
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("Weather forecast")
println(getWeatherReport())
println("Have a good day!")
}
}
suspend fun getWeatherReport() = coroutineScope {
val forecast = async { getForecast() }
val temperature = async { getTemperature() }
"${forecast.await()} ${temperature.await()}"
}
suspend fun getForecast(): String {
delay(1000)
return "Sunny"
}
suspend fun getTemperature(): String {
delay(1000)
return "30\u00b0C"
}
code:出力
Weather forecast
Sunny 30°C
Have a good day!