Home > Mobile >  How does this kotlin coroutine code works?
How does this kotlin coroutine code works?

Time:12-10

I have these two suspend functions

suspend fun doSomethingUsefulOne(): Int {
        delay(3000L) 
        return 20
    }

suspend fun doSomethingUsefulTwo(): Int {
        delay(3000L) 
        return 10
    }

I wanted to run both the functions parallelly so I'm running the below code. In this case I'm getting the result in ~3 seconds

 runBlocking {
            val a = async { doSomethingUsefulOne() }
            val b = async { doSomethingUsefulTwo() }
            println(a.await() b.await())
        }

But when I tried to use the below function, I am getting the result after ~6 sec. Why is that so?

runBlocking {
   println(async { doSomethingUsefulOne() }.await() async { doSomethingUsefulTwo() }.await())
        }

CodePudding user response:

The numeric plus operator requires the left side of the operation to be executed before the right side is evaluated. This means that the right side operation, including the async is delayed until the left side is fully evaluated in the statement (this includes the await on the left side, which takes the full 3 seconds.

Take for instance the expression

someBooleanResponse(a, b, c) || someOtherBooleanExpression(d, e)

On this expression, the left side someBooleanResponse will be fully evaluated, before the right side is even started. This is (ab)used in scripts sometimes to make it a condition.

The same is true for your example. The right side is being held until the left side is completed. If for example the left side threw an exception, the right side would never be needed.

To solve this, you need to execute both async statements before await is called. Otherwise the second async will not even start and therefore you wait another 3 seconds.

  • Related