Java8 CompletableFuture recoverWith equivalent? for example, exclusively, but return CompletableFuture <U>
I do not see an obvious way to handle an exception with an asynchronous result. For example, if I want to repeat the async operation. I would expect something similar, however handleAsync does not do what you think it does - it starts callbacks in another thread asynchronously. The return of the CompletionStage here is incorrect. Dangerous question of the day: thenApply is exclusively how thenCompose is for what.
CompletionStage<String> cf = askPong("cause error").handleAsync((x, t) -> { if (t != null) { return askPong("Ping"); } else { return x; } }); Where askPong asks the actor:
public CompletionStage<String> askPong(String message){ Future sFuture = ask(actorRef, message, 1000); final CompletionStage<String> cs = toJava(sFuture); return cs; } Is this what you are looking for?
askPong("cause error") .handle( (pong, ex) -> ex == null ? CompletableFuture.completedFuture(pong) : askPong("Ping") ).thenCompose(x -> x); Also, do not use ...Async methods unless you plan to execute the body of the function asynchronously. So when you do something like
.handleAsync((x, t) -> { if (t != null) { return askPong("Ping"); } else { return x; }) You are requesting if-then-else run in a separate thread. Since askPong returns a CompletableFuture , there is probably no reason to run it asynchronously.
After much disappointment in trying to figure out the right way to make Scala recoverWith in Java 8, I ended up just writing my own. I still don't know if this is the best approach, but I created something like:
public RecoveryChainAsync<T> recoverWith(Function<Throwable, CompletableFuture<T>> fn); On repeated calls to recoverWith, I queue the functions inside the recovery chain and implement the recovery stream myself using "handle". RecoveryChainAsync.getCompletableFuture () then returns a CompletableFuture representative for the entire chain. Hope this helps.