Reduce a list of objects to an object with a string list member in CompletableFuture's thenApply

Viewed 25

In the following code, parallel requests to send notifications are built using CompletableFuture instances. These futures are chained and I would like to produce an SmsDetails object with msisdns by reducing the returned objects from individual futures. How can I achieve that?

@Override
public SmsDetails send(SmsDetails smsDetails) {
    List<CompletableFuture<MibsReturn>> completableFutures =
            smsDetails.getDestinations().stream().map(msisdn -> getMibsReturns(msisdn, smsDetails.getMessage(), smsDetails.getSource())).collect(Collectors.toList());
    CompletableFuture<Void> allFutures = CompletableFuture
            .allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]));
    CompletableFuture<List<MibsReturn>> allCompletableFuture = allFutures.thenApply(future -> {
        return completableFutures.stream()
                .map(completableFuture -> completableFuture.join())
                .collect(Collectors.toList());
    });
    CompletableFuture completableFuture = allCompletableFuture.thenApply({
            //code to reduce
    });
    SmsDetails returnSmsDetails = completableFuture.get();
    return returnSmsDetails;
}

private CompletableFuture<MibsReturn> getMibsReturns(String msisdn, String message, String senderId) {
    return CompletableFuture.supplyAsync( () -> {
        return sendViaMibs(msisdn, message, senderId);
    });
}
0 Answers
Related