Kotlin Coroutinesで非同期に処理を複数開始して全ての結果を待つ
例えばListの各値に対して非同期に処理を開始してその全ての結果を待って通知したいとする。 こういったときはcoroutineScope内でListの項目ごとにasyncしてdeferredのlistを作りawaitAll()すればよい。結果もListとして受け取ることができる。
suspend fun execute() { coroutineScope { val deferredList = list.map { item -> async { api.execute(item.id) } // Deferred<ExecuteResult> } val result: List<ExecuteResult> = deferredList.awaitAll() ... }