import kotlinx.coroutines.*
suspend fun fetchUserAge(id: Int): Int {
delay(200)
return id * 10
}
suspend fun fetchUserName(id: Int): String {
delay(150)
return "User $id"
}
fun main() = runBlocking {
val start = System.currentTimeMillis()
// Parallel — both calls overlap; total wall time ≈ max(200, 150) = 200ms
val nameDeferred = async { fetchUserName(42) }
val ageDeferred = async { fetchUserAge(42) }
val name = nameDeferred.await()
val age = ageDeferred.await()
println("$name is $age years old (${System.currentTimeMillis() - start}ms)")
// Shortcut for "run these N suspends in parallel, collect results"
val parallel = listOf(1, 2, 3).map { async { fetchUserName(it) } }.awaitAll()
println(parallel)
}
Create a free account and build your private vault. Share publicly whenever you want.