I'm trying to write a parallelMap implementation with coroutines. So far I have
suspend fun <T, R> Iterable<T>.parallelMapCoroutine(f: (T) -> R): List<R> =
coroutineScope {
map {
async { f(it) }
}.map { deferred -> deferred.await() }
}
Now as I understand it, this can't return until all the async tasks have returned, because I need to await
them to get their values? But it feels like I should be able to return a Deferred<List>
, like I can with CompletableFuture
s in Java.
Convert from List<CompletableFuture> to CompletableFuture<List>
Or is there a better way to achieve my aim?
`. `async { f(it) }` will return a deferred object. Each of these objects will be computed by a coroutine when you seek a `Deferred
`, the list has to be computed by a single coroutine.
> which can call `await` on?