java - 可完成的 future | thenApply 与 thenCompose

标签 java java-8 completable-future

我无法理解 thenApplythenCompose 之间的区别。

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

来自 Java 文档:

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

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)

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

我知道 thenCompose 的第二个参数扩展了 thenApply 没有的 CompletionStage。

有人可以提供一个示例,在这种情况下我必须使用 thenApply 以及何时使用 thenCompose

最佳答案

thenApply 如果您有同步映射功能,则使用。

CompletableFuture<Integer> future = 
    CompletableFuture.supplyAsync(() -> 1)
                     .thenApply(x -> x+1);
如果您有异步映射函数(即返回 CompletableFuture 的函数),则使用

thenCompose。然后它将直接返回带有结果的 future ,而不是嵌套的 future 。

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

关于java - 可完成的 future | thenApply 与 thenCompose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43019126/

相关文章:

java - 实现网格 RecyclerView 的最佳方式,其中项目是方形图像,下面有一些文本

java - 检测主要 Activity 中 fragment 的 onclick

foreach - 迭代嵌套集合以查找与条件匹配的第一个子子子元素

java - 多类路径规范 - 无法创建 Java 虚拟机

java - 在 Java 中这两种转换方式有什么区别?

java - Java 8 中钻石探测解析或多重继承的规则

java - 使用 Stream API 对两个集合进行叉积

java - CompletableFuture 是否保证在新线程中运行?

java - 期望这两个 CompletableFutures 得到相同的结果

java - 直接从 CompletableFuture.thenAccept 返回值