so usually when you have to make different API calls and wait, you do something like this:
viewModelScope.launch {
withContext(dispatcherProvider.heavyTasks) {
val apiResponse1 = api.get1() //suspend function
val apiResponse2 = api.get2() //suspend function
if (apiResponse1.isSuccessful() && apiResponse2.isSuccessful() { .. }
}
}
but what happens if I've to do multiple concurrent same API Calls with different parameter:
viewModelScope.launch {
withContext(dispatcherProvider.heavyTasks) {
val multipleIds = listOf(1, 2, 3, 4, 5, ..)
val content = arrayListOf<CustomObj>()
multipleIds.forEach { id ->
val apiResponse1 = api.get1(id) //suspend function
if (apiResponse1.isSuccessful()) {
content.find { it.id == id }.enable = true
}
}
liveData.postValue(content)
}
}
Problem with second approach is that it will go through all ids of multipleIds
list and make async calls, but content
will be posted probably before that. How can I wait all the responses from for each loop to be finished and only then postValue
of the content to view?
async
and awaiting on theme will help – Emplace