我无法理解 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.
我知道 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/