我无法理解thenApply(和之间的区别thenCompose().
那么,有人可以提供有效的用例吗?
来自Java文档:
thenApply(Function<? super T,? extends U> fn)
Run Code Online (Sandbox Code Playgroud)
返回一个新的
CompletionStage,当该阶段正常完成时,将使用此阶段的结果作为所提供函数的参数执行.
thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
Run Code Online (Sandbox Code Playgroud)
返回一个新的
CompletionStage,当此阶段正常完成时,将使用此阶段作为所提供函数的参数执行.
我得到的第二个参数thenCompose扩展了CompletionStage,thenApply而不是.
有人可以提供一个例子,我必须使用thenApply何时使用thenCompose?
Given this piece of code:
public List<String> findPrices(String product){
List<CompletableFuture<String>> priceFutures =
shops.stream()
.map(shop -> CompletableFuture.supplyAsync(
() -> shop.getPrice(product), executor))
.map(future -> future.thenApply(Quote::parse))
.map(future -> future.thenCompose(quote ->
CompletableFuture.supplyAsync(
() -> Discount.applyDiscount(quote), executor
)))
.collect(toList());
return priceFutures.stream()
.map(CompletableFuture::join)
.collect(toList());
}
Run Code Online (Sandbox Code Playgroud)
This part of it:
.map(future -> future.thenCompose(quote ->
CompletableFuture.supplyAsync(
() -> Discount.applyDiscount(quote), executor
)))
Run Code Online (Sandbox Code Playgroud)
Could it be rewrite as:
.map(future ->
future.thenComposeAsync(quote -> Discount.applyDiscount(quote), executor))
Run Code Online (Sandbox Code Playgroud)
I took this code from an example of a book and says the two solutions are …