本文介绍了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)





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



我得到了 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:25
查看更多