加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – CompletableFuture |然后应用vs thenCompose

发布时间:2020-12-14 23:57:14 所属栏目:Java 来源:网络整理
导读:我不能让我的头围绕thenApply()和thenCompose()之间的区别. 那么有人可以提供一个有效的用例吗? 从Java文档: thenApply(Function? super T,? extends U fn) Returns a new CompletionStage that,when this stage completes normally,is executed with this
我不能让我的头围绕thenApply()和thenCompose()之间的区别.

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

从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,is executed with this stage as the argument to the supplied
function.

我得到thenCompon的第二个参数扩展了CompletionStage,然后应用不会.

有人可以提供一个例子,在这种情况下,我必须使用然后应用,当thenCompose?

解决方法

那么如果你有一个同步映射函数,那么应用它.
CompletableFuture<Integer> future = 
    CompletableFuture.supplyAsync(() -> 1)
                     .thenApply(x -> x+1);

那么如果你有一个异步映射函数(即返回一个CompletableFuture的函数),那么使用该函数.然后它将直接返回结果,而不是嵌套的未来.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读