How can make this network calls run simultaneously...
# coroutines
k
How can make this network calls run simultaneously using Retrofit and Coroutines
s
Copy code
lifecycleScope.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 ... 
        }
k
but here all responses are diffrent types, so while iterating i also have to check type
s
combine(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
.
k
please can you share any example of this
s
Copy code
lifecycleScope.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())
        }
👍 1
k
so does it pass result in lambda ?
s
suspend fun <A> Deferred<A>.await(): A
So basically what you do here is you start 3
async
tasks, and while they’re running in parallel you
await
them sequentially.
k
yes, i think this can work best, thank you very much for your help 👍
s
Glad I could help 👍