Advertisement
Simonegaita

Weather Coroutines with Exception

Aug 28th, 2023
1,569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.75 KB | None | 0 0
  1. import kotlinx.coroutines.*
  2.  
  3. fun main() {
  4.     runBlocking {
  5.         println("Weather forecast")
  6.         println(getWeatherReport())
  7.         println("Have a good day!")
  8.     }
  9. }
  10.  
  11. suspend fun getWeatherReport() = coroutineScope {
  12.     val forecast = async { getForecast() }
  13.     val temperature = async {
  14.         try {
  15.             getTemperature()
  16.         } catch (e: AssertionError) {
  17.             println("Caught exception $e")
  18.             "{ No temperature found }"
  19.         }
  20.     }
  21.  
  22.     "${forecast.await()} ${temperature.await()}"
  23. }
  24.  
  25. suspend fun getForecast(): String {
  26.     delay(1000)
  27.     return "Sunny"
  28. }
  29.  
  30. suspend fun getTemperature(): String {
  31.     delay(500)
  32.     throw AssertionError("Temperature is invalid")
  33.     return "30\u00b0C"
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement