gpt4 book ai didi

android - 使用协程进行多次循环调用

转载 作者:行者123 更新时间:2023-12-02 12:51:37 25 4
gpt4 key购买 nike

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

我想一次调用几个页面。因为 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())
}
}
}

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

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

最佳答案

我做了 @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()
}
}

关于android - 使用协程进行多次循环调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60686972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com