google-developer-training / basic-android-kotlin-compose-training-race-tracker

Apache License 2.0
32 stars 35 forks source link

Android Basics: Introduction to Coroutines in Kotlin Playground #18

Open MelSardes opened 8 months ago

MelSardes commented 8 months ago

In the part 4.Exception and Cancelation at the section Cancelation, when executing this piece of code :

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

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

    delay(200)
    temperature.cancel()

    "${forecast.await()} ${temperature.await()}"
}

fun main() {
    val time = measureTimeMillis {
        runBlocking {
            println("Weather forecast")
            println(getWeatherReport())
            println("Have a good day!")
        }
    }
    println("Execution time ${time / 1000.0} seconds")   
}

I have the following issue:

Weather forecast
Exception in thread "main" kotlinx.coroutines.JobCancellationException: DeferredCoroutine was cancelled
 at kotlinx.coroutines.JobSupport.cancel (JobSupport.kt:1558) 
 at kotlinx.coroutines.Job$DefaultImpls.cancel$default (Job.kt:199) 
 at FileKt$getWeatherReport$2.invokeSuspend (File.kt:19) 
Caused by: kotlinx.coroutines.JobCancellationException: DeferredCoroutine was cancelled
at kotlinx.coroutines.JobSupport .cancel(JobSupport.kt:1558)
at kotlinx.coroutines.Job$DefaultImpls .cancel$default(Job.kt:199)
at FileKt$getWeatherReport$2 .invokeSuspend(File.kt:19)

I am supposed to have the following message :

Weather forecast
Sunny
Have a good day!