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

Kulwinder Singh

07/13/2019, 11:49 AM
How can make this network calls run simultaneously using Retrofit and Coroutines
s

streetsofboston

07/13/2019, 1:24 PM
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

Kulwinder Singh

07/13/2019, 3:43 PM
but here all responses are diffrent types, so while iterating i also have to check type
s

simon.vergauwen

07/13/2019, 3:45 PM
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

Kulwinder Singh

07/13/2019, 3:55 PM
please can you share any example of this
s

simon.vergauwen

07/13/2019, 3:55 PM
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

Kulwinder Singh

07/13/2019, 3:57 PM
so does it pass result in lambda ?
s

simon.vergauwen

07/13/2019, 3:58 PM
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

Kulwinder Singh

07/13/2019, 4:02 PM
yes, i think this can work best, thank you very much for your help 👍
s

simon.vergauwen

07/13/2019, 4:02 PM
Glad I could help 👍