본문 바로가기

Kotlin/안드로이드 공부

코루틴 플레이그라운드 - 예외처리

728x90

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

fun main() {
    val time = measureTimeMillis {
        runBlocking{ // 동기 (람다 내의 모든 작업이 완료될 때까지 반환되지 않는다.)
            println("Weather forecast")
            try {
                getWeatherReport()
            } catch(e: AssertionError) {
                println("Caught exception in runBlocking(): $e")
                println("Report unavailable at this time")
            }
            println("Have a good day!")
        } 
    }
    println("${time/1000.0}")
}

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

suspend fun getTemperature():String {
    delay(500)
    throw AssertionError("Temperature is invalid")
    return "30\u00b0C"
}

suspend fun getWeatherReport() = coroutineScope { 
    // 실행된 코루틴을 포함한 모든 작업이 완료된 후에만 반환된다.
    // 호출자에는 함수가 동기 작업처럼 보인다.
    
    val forecast = async{getForecast()} // 생산자
    val temperature = async {
        try {
            getTemperature()
        } catch (e: AssertionError) { // 특정 에러 포착하기
            println("Caught exception $e")
            "{ No temperature found }"
        }
    }
    println("${forecast.await()} ${temperature.await()}") // 소비자
    // 생산자에 예외가 있으면 소비자는 예외 처리하지 않을 경우 예외를 얻고 코루틴 실패
    // 생산자에서 예외 처리하면 소비자에 예외 표시되지 않음
}