Shashank
08/26/2019, 5:22 PMrunBlocking {
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.streetsofboston
08/26/2019, 5:23 PMShashank
08/26/2019, 5:26 PMstreetsofboston
08/26/2019, 5:29 PMasync
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
).Sam Schilling
08/26/2019, 5:33 PMval two = async(start = CoroutineStart.LAZY) { function2() }
Shashank
08/26/2019, 5:33 PMDominaezzz
08/26/2019, 5:34 PMawait()
before the scope exits. Otherwise you get deadlock.Shashank
08/26/2019, 5:35 PMDominaezzz
08/26/2019, 5:35 PMShashank
08/26/2019, 5:35 PMstreetsofboston
08/26/2019, 5:36 PMShashank
08/26/2019, 5:37 PMDominaezzz
08/26/2019, 5:38 PMawait()
, seems fair.runBlocking {
val one = async(start = CoroutineStart.LAZY) {
function1()
}
val two = async {
function2()
delay(1000)
one.await()
}
}
Shashank
08/26/2019, 5:42 PMstreetsofboston
08/26/2019, 5:43 PMasync(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………await
has not been called and a risk of deadlock is there.Dominaezzz
08/26/2019, 5:46 PM