-
-
Save theboreddev/1aacf1b00e70760a498f29592b93a8fa to your computer and use it in GitHub Desktop.
coroutines-success
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
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