I have several CompletionStage methods that I\'d like to chain. The problem is that the result of the first one will determine if the next ones should be execut
If you have to check only for null values you can solve using Optional. For example you should do:
public Bar execute(String id) {
return this.getFooById(id)
.thenCompose(this::checkFooPresent)
.thenCompose(this::doSomethingElse)
.thenCompose(this::doSomethingElseMore)
.thenApply(rankRes -> new Bar(foo));
}
private Optional getFooById(String id) {
// some better logic to retrieve foo
return Optional.ofNullable(foo);
}
private CompletableFuture checkFooPresent(Optional optRanking) {
CompletableFuture future = new CompletableFuture();
optRanking.map(future::complete).orElseGet(() -> future.completeExceptionally(new Exception("Foo not present")));
return future;
}
The checkFooPresent() receives an Optional, and if its value is null it complete exceptionally the CompletableFuture.
Obviously you need to manage that exception, but if you have previously setted an ExceptionHandler or something similar it should come for free.