打破CompletableFuture的流程 [英] Break the flow of CompletableFuture

查看:151
本文介绍了打破CompletableFuture的流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have certain flow that runs async using the CompletableFuture, e.g.:

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

所以如果我的 foo()返回 null (以后)我需要很快打破,否则,流程会继续。

So if my foo() returns null (in a future) I need to break very soon, otherwise, the flow continue.

For现在我必须在每个未来的块中检查 null ;但这很难看。

For now I have to check for null all the way, in every future block; but that is ugly.

会不会这可以用 CompletableFuture

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

With CompletableFuture you can define your flow of async tasks, that are executed one after the other. For example, you may say:


做A,当A完成时,做B,然后做C ......

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

我的问题是打破这个流和说:

My question is about breaking this flow and saying:


执行A,但是如果结果为空中断;否则做B,然后做C ......

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

这就是我打破流量的意思。

This is what I meant by 'breaking the flow`.

推荐答案

您的问题很一般,所以答案可能并不完全适用于您。解决此问题的方法有很多种,可能适用于不同情况。

Your question is very general, so the answer might not exactly apply to you. There are many different ways to address this that might be appropriate in different situations.

在评估 CompletableFuture .thenCompose

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

这篇关于打破CompletableFuture的流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆