I have a method doTransmit
which returns a CompletableFuture<T>
. I want to call doTransmit
in a loop and collect all the CompletableFuture<T>
and convert into a CompletableFuture<List<T>>
which resolves with the List<T>
when all the collected CompletableFuture<T>
have been resolved.
CompletableFuture<DeliveryResponse> doTransmit(Notification notification, Receiver receiver, ContentMutator contentMutator) {
//send notification to this receiver
}
CompletableFuture<List<DeliveryResponse>> doTransmit(Notification notification, List<Receiver> receivers, ContentMutator contentMutator) {
List<CompletableFuture<DeliveryResponse>> completableFutures = new ArrayList<>();
receivers.forEach(receiver -> completableFutures.add(doTransmit(notification.clone(), receiver, contentMutator)));
CompletableFuture<List<DeliveryResponse>> listCompletableFuture = CompletableFuture.supplyAsync(ArrayList::new);
completableFutures.forEach(
completableFuture ->
completableFuture.thenCombine(listCompletableFuture,
((deliveryResponse, deliveryResponses) -> deliveryResponses.add(deliveryResponse))
)
);
return listCompletableFuture;
}
But when I call the second doTransmit(notification, receivers, null).thenAccept(list -> System.out.println(list.size()));
the list received is empty.
I am new to the CompletableFuture
concept. However, I know Javascript Promises. Please help.
>`... The `T`s will have already been calculated.