I have two functions that each return CompletebleFuture<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 CompletablyFuture<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());
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With