java – CompletableFuture |然后应用vs thenCompose

我不能让我的头围绕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, when this stage completes
normally, 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));

转载注明原文:java – CompletableFuture |然后应用vs thenCompose - 代码日志