Break the flow of CompletableFuture

拜拜、爱过 提交于 2019-12-22 06:45:23

问题


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

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

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

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

Would this be possible with CompletableFuture?

EDIT

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

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

My question is about breaking this flow and saying:

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

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


回答1:


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.

One way to create a branch in evaluation of CompletableFuture is with .thenCompose:

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


来源:https://stackoverflow.com/questions/31125117/break-the-flow-of-completablefuture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!