【问题标题】:Multiple loop calls with coroutines使用协程进行多次循环调用
【发布时间】:2020-03-14 20:21:47
【问题描述】:

我需要并行进行多次调用,并且只有在协程一切都成功时才发送结果

我想同时调用几个页面。因为 API 有 4 个页面,我想一次性带上所有结果。

我设法像这样手动完成:

private fun fetchList() {
    viewModelScope.launch {
        val item1 = async { repository.getList(1)!! }
        val item2 = async { repository.getList(2)!! }
        val item3 = async { repository.getList(3)!! }
        val item4 = async { repository.getList(4)!! }

        launch {
            mutableLiveDataList.success(item1.await() + item2.await() + item3.await() + item4.await())
        }
    }
}

但是当我尝试循环播放它时,它只会打开其中一页。

API:

@GET("cards")
suspend fun getListCards(@Query("set") set: String, @Query("page") page: Int): CardsResponse

【问题讨论】:

  • 您确定其他页面不为空吗?此外,您发布的“API”与 fetchList 中使用的不同。
  • 在我的视图模型中,他显示了总数并说正确的数量即将到来。 api的名称不同,因为我在存储库中调用了服务,而函数的名称最终是这样放的。暂停乐趣 getList(page: Int) : List?{ return apiService.getListCards("2ED", page).cards }
  • 您的代码在我看来是正确的。在那里放置断点,然后查看 repository.getList(2) 返回的内容。
  • 您的最后一个(嵌套)launch 是多余的。同一个协程可以启动异步任务并在最后等待它们。
  • 另外,您可以使用pageNumbers.map { async { repository.getList(it} } }.awaitAll() 简化此代码。您确实必须包含 supervisorScopecoroutineScope,具体取决于您希望其中一个提取失败如何影响其余部分。

标签: android multithreading kotlin kotlin-coroutines


【解决方案1】:

我按照@curioustechizen 所说的做了,并且成功了。

这是一个外观示例:

private fun fetchList() {
    viewModelScope.launch {

        val listPageNumbers = arrayListOf<Int>()
        (1..4).forEach { listPageNumbers.add(it) }

        listPageNumbers.map {
            delay(1000)
            async {
                mutableLiveDataList.success(repository.getListCards(it)!!)
            }
        }.awaitAll()
    }
}

【讨论】:

  • 您可以进一步简化它:您根本不需要listPageNumbers 变量。 (1..4).map { } 应该可以工作。
猜你喜欢
  • 2015-06-25
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2019-03-10
相关资源
最近更新 更多