Kamila
03/31/2022, 6:53 AMprivate suspend fun fetchExternalData(futures: List<CompletableFuture<Reply>>): List<Reply> = coroutineScope {
futures.map {
async {
it.join()
}
}.awaitAll()
}
I have a list of CompletableFuture, which I would run async and do action when all of them complete. Is this the right place where I call join
(or get()
) to get reply?
The idea is to get a bunch of request, send them in parallel (fork) and wait for all of them (join), then combine the resultJoffrey
03/31/2022, 6:59 AMjoin()
in coroutines. A better option is to use the CompletableFuture.await()
function provided by kotlinx-coroutines-jdk8
asDeferred()
directly instead of async { it.await() }
ephemient
03/31/2022, 7:02 AMprivate suspend fun fetch(futures: List<CompletableFuture<Reply>>): List<Reply> =
futures.map { it.asDeferred() }.awaitAll()
the basic idea is sound, but asDeferred()
also ties cancellation back to the original Future
Joffrey
03/31/2022, 7:09 AMCompletableFuture.await
and asDeferred
forward cancellation to the underlying future. Using join
doesn't.ephemient
03/31/2022, 7:13 AMJoffrey
03/31/2022, 7:15 AMasDeferred().await()
does not forward cancellation. So I guess Deferred.await()
is cancellable but doesn't cancel the underlying Deferred
? Weird..Kamila
03/31/2022, 8:59 AM