Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten Java Futures

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.

like image 991
Dan Midwood Avatar asked Apr 25 '14 20:04

Dan Midwood


2 Answers

Just use the method thenCompose instead of thenApply:

CompletableFuture<Boolean> result = doA().thenCompose(b -> b
    ? CompletableFuture.completedFuture(Boolean.TRUE) : doB());
like image 72
nosid Avatar answered Oct 31 '22 08:10

nosid


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());
}
like image 29
Matthias Braun Avatar answered Oct 31 '22 10:10

Matthias Braun