Sobes.tech
Back to tasks
Junior — Senior
43

Разбор поведения корутин в Kotlin – пример 3

Get help with live coding in real time with Sobes Copilot
Task condition

Нужно предсказать, какой вывод будет получен при запуске следующего кода.

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() }

    delay(200)
    temperature.cancel()
    "${forecast.await()}"
}

suspend fun getForecast(): String {
    delay(1000)
    return "Sunny"
}

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