将List <completablefuture <t >>转换为CompletableFuture <list <t >>

时间:2019-01-25 09:46:19

标签: java asynchronous java-8 completable-future

我有一个方法doTransmit,它返回一个CompletableFuture<T>。我想循环调用doTransmit并收集所有CompletableFuture<T>并转换成CompletableFuture<List<T>>并在所有收集到的List<T>都用完后用CompletableFuture<T>解析的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; } 解决。

doTransmit(notification, receivers, null).thenAccept(list -> System.out.println(list.size()));

但是当我拨打第二个CompletableFuture时,收到的列表为空。

我是$post_id = 1; $user_ip = '0.0.0.0'; add_post_meta( $post_id, 'my_vote', $user_ip ); 概念的新手。但是,我知道Javascript承诺。请帮忙。

1 个答案:

答案 0 :(得分:1)

您需要一个Supplier<List<DeliveryResponse>>来收集响应:

// your code
List<CompletableFuture<DeliveryResponse>> completableFutures = new ArrayList<>();
receivers.forEach(receiver -> completableFutures.add(doTransmit(notification.clone(), receiver, contentMutator)));

Supplier<List<DeliveryResponse>> responseCollector = () -> {
    List<DeliveryResponse> result = new ArrayList<>();
    // get the result for each... I think you need to try-catch this
    receivers.forEach(r -> result.add(r.get());
    return result;
}

,然后从中创建一个CompletableFuture

CompletableFuture<List<DeliveryResponse>> listFuture = CompletableFuture.supplyAsync(responseCollector);
return listFuture;

现在listFuture通过为每个期货调用get来收集结果。