How do I run N network calls parallel-ly and wait for their response?
Data {1, 2, 3, ... N} -> Response { Response1, Response2, Response3...ResponseN}
I want to run the tasks parallel-ly and wait for their response separately without losing which response belongs to which data param.
b
bezrukov
03/19/2021, 9:30 AM
Copy code
val dataList = listOf(data1, data2, ... dataN)
coroutineScope {
val responses = dataList.map { data ->
async {
performRequest(data)
}
}.awaitAll()
}
in this case it will wait for all responses. If you want to handle responses asynchronously as well do
Copy code
val dataList = listOf(data1, data2, ... dataN)
coroutineScope { // coroutineScope suspends until all children complete
dataList.forEach { data ->
async {
val response = performRequest()
// handle data & response
}
}
}