CompletableFuture |然后应用vs thenCompose [英] CompletableFuture | thenApply vs thenCompose

查看:476
本文介绍了CompletableFuture |然后应用vs thenCompose的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解 thenApply()和 thenCompose()之间的区别。

I can't get my head around the difference between thenApply() and thenCompose().

那么,有人可以提供有效的用例吗?

So, could someone provide a valid use case?

来自Java文档:

thenApply(Function<? super T,? extends U> fn)




返回一个新的 CompletionStage 当这个阶段正常完成
时,执行此阶段的结果作为
提供函数的参数。

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function.



thenCompose(Function<? super T,? extends CompletionStage<U>> fn)




返回一个新的 CompletionStage ,当这个阶段完成时通常,
在此阶段执行,作为所提供的
函数的参数。

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage as the argument to the supplied function.

我得到了 thenCompose 的第二个参数扩展了CompletionStage,其中 thenApply 没有。

I get that the 2nd argument of thenCompose extends the CompletionStage where thenApply does not.

有人可以提供一个示例,在这种情况下,我必须使用 thenApply ,当时,然后撰写

Could someone provide an example in which case I have to use thenApply and when thenCompose?

推荐答案

thenApply 如果使用你有一个同步映射函数。

thenApply is used if you have a synchronous mapping function.

CompletableFuture<Integer> future = 
    CompletableFuture.supplyAsync(() -> 1)
                     .thenApply(x -> x+1);

如果您有异步,则使用映射函数(即返回 CompletableFuture 的函数)。然后它将直接返回结果的未来,而不是嵌套的未来。

thenCompose is used if you have an asynchronous mapping function (i.e. one that returns a CompletableFuture). It will then return a future with the result directly, rather than a nested future.

CompletableFuture<Integer> future = 
    CompletableFuture.supplyAsync(() -> 1)
                     .thenCompose(x -> CompletableFuture.supplyAsync(() -> x+1));

这篇关于CompletableFuture |然后应用vs thenCompose的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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