简体   繁体   中英

CompletableFuture chaining with exception handling

I am trying to compose a chain of steps such that I can avoid a large nested chain of if and else calls by creating methods that return CompletableFuture<Boolean> in a manner such as....

client.connect(identifier).thenCompose(b -> client.authenticate())
                           .thenCompose(b -> client.sendSetting(settings))
                           .thenCompose(b -> client.saveSettings())
                           .thenCompose(b -> client.sendKey(key))
                           .thenCompose(b -> client.setBypassMode(true))
                           .thenCompose(b -> client.start())
                           .whenComplete((success, ex) -> {
                                 if(ex == null) {
                                     System.out.println("Yay");  
                                 } else {
                                     System.out.println("Nay");   
                                 }
                           });

If the client methods return a CompletableFuture<Boolean> deciding whether to continue processing has to be done in each lambda in the chain and doesn't provide a method to abort early if one of the calls fail. I would rather have the calls return CompletableFuture<Void> and use Exceptions to control if 1) each successive step in the chain executes and 2) final determination of success of the full chain.

I am having trouble finding which method on CompletableFuture<Void> to swap for thenCompose to make things work (let alone compile).

public class FutureChaings {
    public static CompletableFuture<Void> op(boolean fail) {
        CompletableFuture<Void> future = new CompletableFuture<Void>();
        System.out.println("op");
        Executors.newScheduledThreadPool(1).schedule(() -> {
            if(fail) {
                future.completeExceptionally(new Exception());
            }
            future.complete(null);          
        }, 1, TimeUnit.SECONDS); 

        return future;
    }


    public static void main(String[] args) {
        op(false).thenCompose(b -> op(false)).thenCompose(b -> op(true)).whenComplete((b, ex) -> {
            if(ex != null) {
                System.out.println("fail");
            } else {
                System.out.println("success");
            }
        });
    }
}

I was able to contrive an example that behaved the way I wanted. So I know what calls to put together to get what I want. Now to figure out what the compiler doesn't like in my real code. Thanks for the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM