how to make this call parallel , where `init` and ...
# coroutines
k
how to make this call parallel , where
init
and
getLastState
are
suspend
function ?
l
I'd fix the indentation and add a question mark since it's a question. Does the second call work if you remove the first one? If no, then you can't make it parallel by definition. Otherwise, you can just use
async
and
await
.
k
yes, second call not depend on first one and works without it
then how to do ?, i want to do both calls in parallel
is it right way ? ->
Copy code
async { musicProvider.init() }.await()
val lastState = async { musicProvider.getLastState() }.await()
l
If you await before starting the other, it's on longer parallel, and the IDE should warn you BTW.
With a single async block, you can do this:
Copy code
val lastStateAsync = async { musicProvider.getLastState() }
musicProvider.init()
val lastState = lastStateAsync.await()
d
Copy code
listOf(
  async { ... },
  async { ... }
).awaitAll()
Louis' is probably nicer since it doesn't allocate a list, and since you only want the result of
getLastState
, and since async calls now work intuitively with their parent scope if they throw
b
Do you need the result of
init
? (By result I mean was there an exception). If not, just launch that and then use
getLastState
directly
Copy code
uiScope.launch {
    launch { runCatching { musicProvider.init() } }
    val lastState = musicProvider.getLastState()
    ...
}
👍 1