Created
September 24, 2021 04:32
-
-
Save vengateshm/245dfb66da8f09ad71daf3c5d93fa380 to your computer and use it in GitHub Desktop.
Execute coroutines in parallel and wait for result of all coroutines.
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
import kotlinx.coroutines.* | |
import kotlin.random.Random | |
import kotlin.system.measureTimeMillis | |
fun main(args: Array<String>) { | |
val time = measureTimeMillis { | |
runBlocking { | |
val coffeePowder = async { | |
println("Grinding coffee bean...") | |
grindCoffeeBeans() | |
} | |
val hotMilk = async { | |
println("Heating milk...") | |
heatMilk() | |
} | |
// val ingredient1 = coffeePowder.await() | |
// val ingredient2 = hotMilk.await() | |
val (ingredient1, ingredient2) = awaitAll(coffeePowder, hotMilk) | |
println("$ingredient1 + $ingredient2 = Hot Coffee!") | |
} | |
} | |
println("Time ${time / 1000}s") | |
} | |
suspend fun grindCoffeeBeans(): String { | |
delay(1000) | |
return "Coffee powder" | |
} | |
suspend fun heatMilk(): String { | |
delay(1000) | |
return "Hot Milk" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment