Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the time taken different using async and await in a coroutine?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading