I have the code ``` runBlocking { val ...
# announcements
s
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
It is not lazy. Provide LAZY as input to the async call if you like it to be lazy
s
so does it start all the async blocks defined till now?
s
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
val two = async(start = CoroutineStart.LAZY) { function2() }
s
Thanks a lot guys! 🙂
d
Don't forget to explicitly call
await()
before the scope exits. Otherwise you get deadlock.
s
Yeah just got one 😅
d
lol
s
Shouldn't it just finish normally if I never await or start a lazy async?
s
I think it should….. but it doesn’t 🙂
But opinions on this subject vary 🙂
☝🏼 1
s
Interesting. Do you know where I can read up on the "varying" opinions?
d
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
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
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
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.