Junior — Middle
How can you initiate two network requests simultaneously using coroutines and combine their responses?
sobes.tech AI
Answer from AI
To run two network requests simultaneously using coroutines in Android, you can use the async function inside a coroutine, and then combine the results with await. Here's an example in Kotlin:
import kotlinx.coroutines.*
suspend fun fetchData(): Pair<Response1, Response2> = coroutineScope {
val deferred1 = async { networkRequest1() }
val deferred2 = async { networkRequest2() }
val result1 = deferred1.await()
val result2 = deferred2.await()
Pair(result1, result2)
}
suspend fun networkRequest1(): Response1 {
// implementation of the first request
}
suspend fun networkRequest2(): Response2 {
// implementation of the second request
}
Thus, both requests are launched in parallel, and the results are combined after their completion.