完成 Kotlin 中的异步调用列表

Wis*_*sal 7 android kotlin kotlin-coroutines

我们有一个本质上是异步的操作列表。我们想要完成所有操作,可以说,并且想要执行另一项任务。我对 Kotlin 协程概念完全陌生,无法完成这项任务。我在互联网上搜索了很多,但由于我对 kotlin 协程或 kotlin 的另一个异步服务没有总体经验来执行此操作。任何人知道如何完成这项任务都会非常有帮助。假设列表中有 20 个元素,我想对每个元素执行一个本质上异步的操作。

      response.data?.let { dataArray ->

                if (dataArray.isNotEmpty()) {
                    it.forEach {
                        it.unpair().done{
                           // Async call.  
                       }
                    }
              // All async operation completed do another task.
                    
                } else {
                    // Array is empty.
                }
            }
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 9

我认为对列表中的每个项目执行异步任务的一种干净方法是使用mapand then awaitAll。协程恢复后,结果列表包含所有结果。

从协程内部:

val unpackedData = results.data.orEmpty().map {
        async { 
            it.unpair().done() 
            // I don't really know what type of object this is, but you can do anything in 
            // this block and whatever the lambda eventually returns is what the list will 
            // contain when the outer coroutine resumes at the awaitAll() call
        }
    }.awaitAll()
// Make other calls here. This code is reached when all async tasks are done.
Run Code Online (Sandbox Code Playgroud)

orEmpty()函数是一种将可为空列表转换为不可为空列表的便捷方法,通过删除分支使代码更简单。有时它并不真正适用,但通常您可以消除嵌套的 if 语句或提前返回。就像如果您迭代结果数据并且它是空的,那可能完全没问题。


小智 1

确保您在协程范围内运行它

val requests = ArrayList<Deferred<Unit>>()
val dataArray = response.data ?: return

dataArray.forEach { data ->
  data.unpair().done {
    // YOUR METHOD starts running immediately
    requests.add( async { YOUR METHOD } )
  }
}

// Waits for all YOUR METHOD's to finish
requests.awaitAll()
Run Code Online (Sandbox Code Playgroud)