Combining via thenCompose()

Let's assume that we have the following two CompletableFuture instances in a helper class named CustomerAsyncs:

private static CompletableFuture<String> 
fetchOrder(String customerId) {

return CompletableFuture.supplyAsync(() -> {
return "Order of " + customerId;
});
}

private static CompletableFuture<Integer> computeTotal(String order) {

return CompletableFuture.supplyAsync(() -> {
return order.length() + new Random().nextInt(1000);
});
}

Now, we want to fetch the order of a certain customer, and, once the order is available, we want to compute the total of this order. This means that we need to call fetchOrder() and afterward computeTotal(). We can do this via thenApply():

CompletableFuture<CompletableFuture<Integer>> cfTotal 
= fetchOrder(customerId).thenApply(o -> computeTotal(o));

int total = cfTotal.get().get();

Obviously, this is not a convenient solution since the result is of the CompletableFuture<CompletableFuture<Integer>> type. In order to avoid the nesting of CompletableFuture instances, we can rely on thenCompose() as follows:

CompletableFuture<Integer> cfTotal 
= fetchOrder(customerId).thenCompose(o -> computeTotal(o));

int total = cfTotal.get();

// e.g., Total: 734
logger.info(() -> "Total: " + total);
Whenever we need to obtain a flattened result from a chain of CompletableFuture instances, we can use thenCompose(). This way we avoid nested examples of CompletableFuture instances.

Further parallelization can be obtained using thenComposeAsync().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.79.147