Skip to content

Instantly share code, notes, and snippets.

@theboreddev
Created October 23, 2022 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theboreddev/fc5bf42efe86d85c2dca0050eeda2ad1 to your computer and use it in GitHub Desktop.
Save theboreddev/fc5bf42efe86d85c2dca0050eeda2ad1 to your computer and use it in GitHub Desktop.
coroutines-exception
suspend fun main(): Unit {
GlobalScope.async {
val result = sumNumbersToRandomNumbers(1, 10)
println("Task completed with result $result!")
}.await()
}
suspend fun sumNumbersToRandomNumbers(n1: Int, n2: Int): Int =
coroutineScope {
val job1 = async {
delay(1000)
println("Adding random number to $n1")
n1 + nextRandom()
}
val job2 = async {
delay(500)
throw RuntimeException("Something went wrong!")
println("Adding random number to $n2")
n2 + nextRandom()
}
job1.await() + job2.await()
}
private fun nextRandom(): Int = (0..9999).random()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment