https://kotlinlang.org logo
#coroutines
Title
# coroutines
o

Olli Helenius

07/14/2021, 7:19 AM
sorry about a possibly stupid question but is this:
val x = (async { foo() }).await()
ever different from just
val x = foo()
?
e

ephemient

07/14/2021, 7:36 AM
Copy code
var i = 0
launch { i++ }
val x = i

var j = 0
launch { j++ }
val y = async { j }.await()
x == 0 && y == 1
(not guaranteed, but likely in a single threaded dispatcher)
o

Olli Helenius

07/14/2021, 7:40 AM
so does that mean the
async
call is a suspension point?
u

uli

07/14/2021, 7:41 AM
await
is
o

Olli Helenius

07/14/2021, 7:41 AM
ah indeed
but if
foo()
in my example is a
suspend fun
does it make any difference in that case?
u

uli

07/14/2021, 7:43 AM
yes, even in a single threaded dispatcher you can have state changed by other coroutines at each suspension point
o

Olli Helenius

07/14/2021, 7:45 AM
i mean does wrapping the call in
async
make any difference? the call to
foo()
is also a suspension point right?
u

uli

07/14/2021, 7:47 AM
depends on foo. If foo suspends it is. if foo does not suspend it’s not. Calling this
foo
will not suspend:
suspend fun foo(): Int { return 1 }
w

wasyl

07/14/2021, 7:48 AM
iiuc it’s a possible suspension point, it’ll not suspend unless you suspend inside foo
o

Olli Helenius

07/14/2021, 7:50 AM
i see, thanks
5 Views