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

Quy D X Nguyen

05/29/2020, 4:56 AM
Is
async { suspendFunc() }.await()
different from
suspendFunc()
by itself?
g

gildor

05/29/2020, 5:01 AM
mechanism of how it works is different
for example if async failed it will cancel parent Job (for non-Supervisor Job)
but on practice such pattern as:
async { }.await()
is always wrong, I don’t see any valid use case for it
s

serebit

05/29/2020, 5:03 AM
functionally the same as
withContext { }
too
g

gildor

05/29/2020, 5:04 AM
not the same, but to switch context withContext of course is preferrable
q

Quy D X Nguyen

05/29/2020, 5:07 AM
So I can just call
suspendFunc()
and it'll be an async call?
Just worried about accidentally blocking.
g

gildor

05/29/2020, 5:12 AM
if you worry about blocking, check your suspendFunc() implementation
properly written suspend function shouldn’t block
also you always can use withContext(someDispatcher) { suspendFun } to use different dispatcher to be sure that it will not block your current coroutine
👍 1
e

Erik

05/29/2020, 5:18 AM
There is at least one use case for async-await on the same line: https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad Read just above and below the header 'What about something simpler?'
g

gildor

05/29/2020, 5:22 AM
Okay, actually you right, I also used it a few times to make async not-cancellable
exactly for this use case, repository
So yeah, there is this use case, and it more clean imo than usage of non-cancellable coroutine on the same. But it’s clearly not the case of original question
10 Views