打破 CompletableFuture 的流程

Break the flow of CompletableFuture

我有一些使用 CompletableFuture 异步运行的流程,例如:

foo(...)
        .thenAccept(aaa -> {
            if (aaa == null) {
                 break!
            }
            else {
              ...
            }
        })
        .thenApply(aaa -> {
           ...
        })
        .thenApply(...

所以如果我的foo()returnsnull(在未来)我需要尽快中断,否则,流程继续。

现在我必须在以后的每个区块中一直检查 null;但这很难看。

CompletableFuture 可以吗?

编辑

使用 CompletableFuture 您可以定义一个接一个执行的异步任务流。例如,您可以说:

Do A, and when A finishes, do B, and then do C...

我的问题是关于中断此流程并说:

Do A, but if result is null break; otherwise do B, and then do C...

这就是我所说的“打破常规”的意思。

您的问题很笼统,所以答案可能不完全适用于您。有许多不同的方法可以解决这个问题,这些方法可能适用于不同的情况。

CompletableFuture 的计算中创建分支的一种方法是使用 .thenCompose:

foo().thenCompose(x -> x == null
        ? completedFuture(null)
        : completedFuture(x)
            .then.....(...)
            .then.....(...)
).join();