【发布时间】:2020-01-16 07:14:32
【问题描述】:
我正在尝试使用 Kotlin Coroutines + Retrofit 进行网络调用,但我目前的实现有两个问题。
A) 它只会在我的循环完成后返回。
B) 它似乎要等待循环中的每个调用完成,然后再进行下一个调用。
我正在与之交互的 API 要求我进行初始提取,返回一个 itemId 的数组
[ 1234, 3456, 3456 ... ]
对于上述响应中的每个项目,使用 id 获取该项目
{ id: 1234, "name": "banana" ... }
我目前的实现如下,我做错了什么?
suspend operator fun invoke(feedType: String): NetworkResult<List<MyItem>> = withContext(Dispatchers.IO) {
val itemList: MutableList< MyItem > = mutableListOf()
val result = repository.fetchItems()
when (result) {
is NetworkResult.Success -> {
itemList.addAll(result.data)
for (i in itemList) {
val emptyItem = result.data[i]
val response = repository.fetchItem(emptyItem.id)
when (response) {
is NetworkResult.Success -> {
val item = response.data
emptyItem.setProperties(item)
}
}
}
}
is NetworkResult.Error -> return@withContext result
}
return@withContext NetworkResult.Success(itemList)
}
【问题讨论】:
-
你想让函数返回循环完成吗?那么它不应该是一个挂起函数。
标签: android kotlin kotlin-coroutines