Skip to content

Instantly share code, notes, and snippets.

@vengateshm
Created September 24, 2021 04:32
Show Gist options
  • Save vengateshm/245dfb66da8f09ad71daf3c5d93fa380 to your computer and use it in GitHub Desktop.
Save vengateshm/245dfb66da8f09ad71daf3c5d93fa380 to your computer and use it in GitHub Desktop.
Execute coroutines in parallel and wait for result of all coroutines.
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