Flatten Java Futures
Just use the method thenCompose
instead of thenApply
:
CompletableFuture<Boolean> result = doA().thenCompose(b -> b
? CompletableFuture.completedFuture(Boolean.TRUE) : doB());
If the creation of the nested future is beyond your control, you can flatten it like this:
static <T> CompletableFuture<T> flatten(
CompletableFuture<CompletableFuture<T>> nestedFuture) {
return nestedFuture.thenCompose(Function.identity());
}