I have a question while learning coroutines.
fun main() {
runBlocking {
val time = measureTimeMillis {
val a = async {
delay(1000)
"1"
}
val b = async {
delay(1000)
"2"
}
val a1 = a.await()
val b1 = b.await()
}
println(time)
}
}
Running this takes 1000
fun main() {
runBlocking {
val time = measureTimeMillis {
val a = async {
delay(1000)
"1"
}.await()
val b = async {
delay(1000)
"2"
}.await()
}
println(time)
}
}
but Running this takes 2000
I’d like to know why this is happening
Does the behavior change depending on returning Deferred versus returning a value after execution?
>Solution :
From async docs
By default, the coroutine is immediately scheduled for execution.
In first case you simply launch two coroutines with async, which start executing immediately, by the time you call await on both of them they are up and running. so they both take only 1000 millis to complete.
but in second case you launch a and then wait for it to finish, this takes 1000 millis and then you start b and wait for it to finish, which also takes 1000 millis. so ultimatly this costs you 2000 millis.