Predict the output
Each call takes 1 second. Roughly how long until both are printed?
fun main() = runBlocking {
val start = System.currentTimeMillis()
val a = async { delay(1_000); "A" }
val b = async { delay(1_000); "B" }
println(a.await() + b.await())
println((System.currentTimeMillis() - start) / 1_000)
}Hint 1 of 2
When does each async block start?
Hint 2 of 2
Do the two delays overlap?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A AB, then 1
Correct. Both async blocks start straight away and wait at the same time.
Why not the others?
- B AB, then 2. That would happen if b started only after a.await() returned.
- C BA, then 1. The string is built in the order of the awaits, so A comes first.
- D It prints 0 because async doesn't start until await. async starts eagerly unless you pass CoroutineStart.LAZY.
Text version
| Version | What runs when | Finishes at |
|---|---|---|
| Two async, then await |
| t = 1.0 s |
| async { }.await() twice |
| t = 2.0 s |