Julien Raad
Julien Raad

Reputation: 51

Kotlin Coroutines - Async Await

In his article about Structured Concurrency in Kotlin (https://medium.com/@elizarov/structured-concurrency-722d765aa952), Roman Elizarov explains parallel decomposition by giving the following example:

coroutineScope { 
    val deferred1 = async { loadImage(name1) }
    val deferred2 = async { loadImage(name2) }
    combineImages(deferred1.await(), deferred2.await())
}

Obviously, this code is self-explanatory. However will we get the same result if we write this instead

coroutineScope { 
    val result1 = async { loadImage(name1) }.await()
    val result2 = async { loadImage(name2) }.await()
    combineImages(result1, result2)
}

Meaning, will both async still run in parallel or the 2nd async call will never run until result1 is available ?

Upvotes: 4

Views: 4438

Answers (1)

Edy Daoud
Edy Daoud

Reputation: 84

Example 1:

fun main(args: Array<String>) = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async {
            delay(1000)
            return@async 1
        }
        val two = async {
            delay(3000)
            return@async 2
        }
        println("The answer is ${one.await() + two.await()}")
    }
    println("Completed in $time ms")
}

Result 1:

The answer is 3
Completed in 3041 ms

Example 2:

fun main(args: Array<String>) = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async {
            delay(1000)
            return@async 1
        }.await()
        val two = async {
            delay(3000)
            return@async 2
        }.await()
        println("The answer is ${one + two}")
    }
    println("Completed in $time ms")
}

Result 2:

The answer is 3
Completed in 4043 ms

Check out this link for the official documentation for Concurrent using async

Conclusion

async-await-async-await will result in pure sequential code

async-async-await-await will run in parallel

Upvotes: 4

Related Questions