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

Kulwinder Singh

11/04/2018, 9:47 AM
how to make this call parallel , where
init
and
getLastState
are
suspend
function ?
l

louiscad

11/04/2018, 9:52 AM
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

Kulwinder Singh

11/04/2018, 9:55 AM
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

louiscad

11/04/2018, 10:10 AM
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

Daniel Tam

11/04/2018, 10:50 AM
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

bdawg.io

11/04/2018, 11:04 PM
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
2 Views