【问题标题】:Kotlin Coroutine Retrofit - Chain network callsKotlin Coroutine Retrofit - 链式网络调用
【发布时间】: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


【解决方案1】:

我建议您使用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 (2)。它可以通过协程和async 轻松完成。然后我们等到所有数据都被提取(3)。

【讨论】:

  • 我喜欢这种“映射”列表并调用 awaitAll 的解决方案。感觉更干净。
猜你喜欢
  • 1970-01-01
  • 2019-10-30
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2022-01-16
相关资源
最近更新 更多