Kulwinder Singh
07/13/2019, 11:49 AMstreetsofboston
07/13/2019, 1:24 PMlifecycleScope.launch {
val response1 = async { api.getResponse1() }
val response2 = async { api.getResponse2() }
val response3 = async { api.getResponse3() }
val totalResponses = listOf(response1, response2, response3).awaitAll()
... iterate over the totalResponses to compute your final result ...
}
Kulwinder Singh
07/13/2019, 3:43 PMsimon.vergauwen
07/13/2019, 3:45 PMcombine(reponse1.await(), reponse2.await(), reponse3.await())
works as well and that way you don’t lose the type information. Here combine
is a simple function (A, B, C) -> D
.Kulwinder Singh
07/13/2019, 3:55 PMsimon.vergauwen
07/13/2019, 3:55 PMlifecycleScope.launch {
val response1: Deferred<Address> = async { api.getResponse1() }
val response2: Deferred<Name> = async { api.getResponse2() }
val response3: Deferred<Age> = async { api.getResponse3() }
val createUser: (Address, Name, Age) -> User = TODO()
val user = createUser(response1.await(), response2.await(), response3.await())
}
Kulwinder Singh
07/13/2019, 3:57 PMsimon.vergauwen
07/13/2019, 3:58 PMsuspend fun <A> Deferred<A>.await(): A
simon.vergauwen
07/13/2019, 3:59 PMasync
tasks, and while they’re running in parallel you await
them sequentially.Kulwinder Singh
07/13/2019, 4:02 PMsimon.vergauwen
07/13/2019, 4:02 PM