CompletableFuture链接与异常处理

问题描述 投票:1回答:1

我正在尝试组合一系列步骤,以便通过创建以某种方式返回if的方法来避免elseCompletableFuture<Boolean>调用的大型嵌套链。

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");   
                                 }
                           });

如果客户端方法返回CompletableFuture<Boolean>,则决定是否必须在链中的每个lambda中继续处理,并且如果其中一个调用失败,则不提供提前中止的方法。我宁愿让调用返回CompletableFuture<Void>并使用Exceptions来控制是否1)链中的每个连续步骤执行以及2)最终确定完整链的成功。

我无法找到CompletableFuture<Void>上的哪个方法来交换thenCompose以使事情有效(更不用说编译)了。

java completable-future
1个回答
0
投票
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");
            }
        });
    }
}

我能够设计一个表达我想要的方式的例子。所以我知道什么叫做拼凑起来得到我想要的东西。现在来弄清楚编译器在我的实际代码中不喜欢什么。感谢您的评论。

© www.soinside.com 2019 - 2024. All rights reserved.