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

dephinera

11/10/2020, 7:48 AM
Hello, What would be the proper pattern to await multiple coroutines with different results? Is there an alternative to awaitAll? I don't like the necessary casting... I was thinking of using joinAll(...) and then
deferred.getCompleted()
, but
getCompleted()
is experimental.
Copy code
viewModelScope.launch(Dispatchers.MAIN) {
    val deferred1 = async { operation1() }
    val deferred2 = async { operation2() }
    val deferred3 = async { operation3() }
    val deferred4 = async { operation4() }

    val results = awaitAll(deferred1, deferred2, deferred3, deferred4)
    
    val res1 = results[0] as? Type1
    val res2 = results[1] as? Type2
    val res3 = results[2] as? Type3
    val res4 = results[3] as? Type4
}
e

ephemient

11/10/2020, 8:24 AM
do you need the awaitAll()?
Copy code
viewModelScope.launch(Dispatchers.MAIN) {
    val deferred1 = async { operation1() }
    val deferred2 = async { operation2() }
    val deferred3 = async { operation3() }
    val deferred4 = async { operation4() }
    val res1 = deferred1.await()
    val res2 = deferred2.await()
    val res3 = deferred3.await()
    val res4 = deferred4.await()
}
d

dephinera

11/10/2020, 8:27 AM
ah.. right. Tthanks!
5 Views