【发布时间】:2020-11-03 14:32:50
【问题描述】:
所以通常当您必须进行不同的 API 调用并等待时,您会执行以下操作:
viewModelScope.launch {
withContext(dispatcherProvider.heavyTasks) {
val apiResponse1 = api.get1() //suspend function
val apiResponse2 = api.get2() //suspend function
if (apiResponse1.isSuccessful() && apiResponse2.isSuccessful() { .. }
}
}
但是如果我必须使用不同的参数进行多个并发的相同 API 调用会发生什么:
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)
}
}
第二种方法的问题是它将遍历multipleIds列表的所有ID并进行异步调用,但content可能会在此之前发布。如何等待每个循环的所有响应完成,然后才能查看 postValue 的内容?
【问题讨论】:
-
也许使用
async并等待主题会有所帮助
标签: android retrofit coroutine kotlin-coroutines suspend