본문 바로가기

Kotlin/안드로이드 공부

코루틴 플레이그라운드 - async

728x90

import kotlinx.coroutines.*
import kotlin.system.*

fun main() {
    val time = measureTimeMillis {
        runBlocking{ // 동기 (람다 내의 모든 작업이 완료될 때까지 반환되지 않는다.)
            println("Weather forecast")
            getWeatherReport()
            println("Have a good day!")
        } 
    }
    println("${time/1000.0}")
}

suspend fun getForecast():String { // 정지 함수는 모든 작업이 완료된 후에만 반환된다.
    delay(1000)// 코루틴이나 다른 정지 함수에서만 호출할 수 있다.
    return "Sunny"
}

suspend fun getTemperature():String {
    delay(1000)
    return "30\u00b0C"
}

suspend fun getWeatherReport() = coroutineScope { 
    // 실행된 코루틴을 포함한 모든 작업이 완료된 후에만 반환된다.
    // 호출자에는 함수가 동기 작업처럼 보인다.
    
    val forecast = async{getForecast()}
    val temperature = async{getTemperature()}
    println("${forecast.await()} ${temperature.await()}")
}