https://kotlinlang.org logo
#announcements
Title
# announcements
s

Shashank

08/26/2019, 5:22 PM
I have the code
Copy code
runBlocking {
        val one = async { function1() }
        val two = async { function2() }
        one.await()
    }
Even though I just call
one.await()
I see that function 2 is executed as well? Can anyone explain why is it so? I was under the impression that calling
await()
is what triggers the execution.
s

streetsofboston

08/26/2019, 5:23 PM
It is not lazy. Provide LAZY as input to the async call if you like it to be lazy
s

Shashank

08/26/2019, 5:26 PM
so does it start all the async blocks defined till now?
s

streetsofboston

08/26/2019, 5:29 PM
A call to
async
runs the Coroutine as soon as possible, unless you provide a different value for its
start
parameter (LAZY). If you do provide the value LAZY, it doesn’t run the Coroutine until
start
or
await
and such is called on the returned
Job
(or
Deferred
).
s

Sam Schilling

08/26/2019, 5:33 PM
val two = async(start = CoroutineStart.LAZY) { function2() }
s

Shashank

08/26/2019, 5:33 PM
Thanks a lot guys! 🙂
d

Dominaezzz

08/26/2019, 5:34 PM
Don't forget to explicitly call
await()
before the scope exits. Otherwise you get deadlock.
s

Shashank

08/26/2019, 5:35 PM
Yeah just got one 😅
d

Dominaezzz

08/26/2019, 5:35 PM
lol
s

Shashank

08/26/2019, 5:35 PM
Shouldn't it just finish normally if I never await or start a lazy async?
s

streetsofboston

08/26/2019, 5:36 PM
I think it should….. but it doesn’t 🙂
But opinions on this subject vary 🙂
☝🏼 1
s

Shashank

08/26/2019, 5:37 PM
Interesting. Do you know where I can read up on the "varying" opinions?
d

Dominaezzz

08/26/2019, 5:38 PM
If you explicitly specify lazy you must explicitly
await()
, seems fair.
Copy code
runBlocking {
    val one = async(start = CoroutineStart.LAZY) {
       function1()
    }
    val two = async {
        function2()
        delay(1000)
        one.await()
    }
}
Library doesn't know if you're going to await at some point, even if the scope has ended.
s

Shashank

08/26/2019, 5:42 PM
Ahh that makes sense. But if the scope has reached the end and I haven't called await, it isn't a far fetched assumption that I don't want to await on that async.
s

streetsofboston

08/26/2019, 5:43 PM
Probably because you could provide the deferred result from
async(start = LAZY)
to an external class/actor/piece-of-code and it could decide to call
await
at any given time, even if it is hours later………
🤔 1
Would be nice to have a compiler/lint warning for local lazy Deferred values, that can detect if
await
has not been called and a risk of deadlock is there.
☝️ 1
d

Dominaezzz

08/26/2019, 5:46 PM
The lint would be just as good as the, "calling blocking IO in non-IO dispatcher" lint.
Although, I guess the library could see that the only coroutines left are the lazy ones.
But what order should they be "awakened" in though?
Too many questions to answer.
3 Views