I have two functions that each return CompletableFuture<Boolean>
instances and I want to or
them into a single ordered and short-circuit-able future.
public CompletableFuture<Boolean> doA();
public CompletableFuture<Boolean> doB();
The non-future code (i.e. returning only booleans) would simply be
return doA() || doB();
Using Futures I have reached this point, when the return type is a CompletableFuture<CompletableFuture<Boolean>>
instance.
doA.thenApply(b -> {
if (!b) {
return doB();
} else {
return CompletableFuture.completedFuture(b);
}
}
Is there a way to flatten this? Or, any way I can make a return type of CompletableFuture<Boolean>
?
Edit: Note, being able to short circuit the futures is a feature that I want. I know that I'm then running the computations in serial, but that's ok. I do not want to run doB
when doA
returns true.
Just use the method thenCompose
instead of thenApply
:
CompletableFuture<Boolean> result = doA().thenCompose(b -> b
? CompletableFuture.completedFuture(Boolean.TRUE) : doB());