Hello, What would be the proper pattern to await m...
# coroutines
d
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
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
ah.. right. Tthanks!