如何对同一端点进行多个 API 并行调用,并将所有响应组合到一个输出数组中?

How do I make multiple API calls in parallel to the same endpoint and combine all the responses into an output array?

目前在我的 Kotlin 代码中,我有一个用户数组,我执行了一个 for 循环并对每个用户的信息发出 GET 请求,然后将他们的信息添加到 MutableList。我观察列表并更新我的 UI 每当新用户信息被 post 编辑到它时。

但我想知道如何同时进行所有用户调用并等待最终结果和 post UI 一次完成?

您可以对它们使用 async syntax to start requests and then awaitAll(请注意,一旦任何延迟失败,它将立即失败)。

类似于:

val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }

val result = awaitAll(one, two) // will give you a list of results

因此,在您的情况下,您可以 map 对用户进行 async 操作。

示例:https://kotlinexpertise.com/kotlin-coroutines-concurrency/

Roman Elisarov 关于结构化并发的博客:https://elizarov.medium.com/structured-concurrency-722d765aa952(关于并行分解的部分)