Frage

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.

War es hilfreich?

Lösung

Just use the method thenCompose instead of thenApply:

CompletableFuture<Boolean> result = doA().thenCompose(b -> b
    ? CompletableFuture.completedFuture(Boolean.TRUE) : doB());

Andere Tipps

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());
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top