可完成的未来 \| thenApply 与 thenCompose

新手上路,请多包涵

我无法 thenApplythenCompose 之间的区别。

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

来自 Java 文档:

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

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

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

返回一个新的 CompletionStage ,当该阶段正常完成时,将以该阶段作为所提供函数的参数执行。

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

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

原文由 GuyT 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

thenApply 如果你有同步映射功能就用。

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

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

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

原文由 Joe C 发布,翻译遵循 CC BY-SA 3.0 许可协议

我认为@Joe C 发布的答案具有误导性。

让我试着用一个例子来解释 thenApplythenCompose 之间的区别。

假设我们有两种方法: getUserInfo(int userId)getUserRating(UserInfo userInfo)

 public CompletableFuture<UserInfo> getUserInfo(userId)

public CompletableFuture<UserRating> getUserRating(UserInfo)

两种方法返回类型都是 CompletableFuture

我们想先调用 getUserInfo() ,并在调用完成后调用 getUserRating() 并得到 UserInfo

在完成 getUserInfo() 方法后,让我们同时尝试 thenApplythenCompose 。区别在于返回类型:

 CompletableFuture<CompletableFuture<UserRating>> f =
    userInfo.thenApply(this::getUserRating);

CompletableFuture<UserRating> relevanceFuture =
    userInfo.thenCompose(this::getUserRating);

thenCompose()Scala 的 flatMap 一样工作,它压平了嵌套的期货。

thenApply() 按原样返回嵌套期货,但是 thenCompose() 扁平化嵌套 CompletableFutures 以便更容易链接更多方法调用

原文由 Dorjee 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题