Kotlin Coroutines Async Await Sequence

val one = async { one() }
val two = async { two() }
val int1 = one.await()
val int2 = two.await()

What this does:

  1. spawn task one
  2. spawn task two
  3. await on task one
  4. await on task two

val one = async { one() }.await()
val two = async { two() }.await()

What this does:

  1. spawn task one
  2. await on task one
  3. spawn task two
  4. await on task two

There’s no concurrency here, it’s purely sequential code. In fact, for sequential execution you shouldn’t even use async. The proper idiom is

val one = withContext(Dispatchers.Default) { one() }
val two = withContext(Dispatchers.Default) { two() }

Leave a Comment