[英]Kotlin Coroutine Retrofit - Chain network calls
我正在嘗試使用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)
}
我想建議您使用async
分別處理每個項目:
suspend operator fun invoke(feedType: String): NetworkResult<List<MyItem>> = withContext(Dispatchers.IO) {
when (val result = repository.fetchItems()) { // 1
is NetworkResult.Success -> {
result.data
.map { async { fetchItemData(it) } } // 2
.awaitAll() // 3
NetworkResult.Success(result.data)
}
is NetworkResult.Error -> result
}
}
private suspend fun fetchItemData(item: MyItem) {
val response = repository.fetchItem(item.id)
if (response is NetworkResult.Success) {
item.setProperties(response.data)
}
}
在此代碼中,首先,我們調用fetchItems
以獲取項目ID(1)。 然后,我們fetchItem
為每個項目調用fetchItem
(2)。 使用協程和async
可以很容易地做到這一點。 然后我們等待,直到所有數據都將被提取(3)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.