thenApply和thenCompose是的方法CompletableFuture。当你打算做些什么来使用他们CompleteableFuture的一个结果Function。
thenApply并且thenCompose都返回一个CompletableFuture作为自己的结果。你可以将多个thenApply或thenCompose在一起。Function为每个调用提供a ,其结果将作为next的输入Function。
在Function你提供的,有时需要同步做一些事情。您的返回类型Function应为非Future类型。在这种情况下,您应该使用thenApply。
CompletableFuture.completedFuture(1)
.thenApply((x)->x+1) // adding one to the result synchronously, returns int
.thenApply((y)->System.println(y)); // value of y is 1 + 1 = 2
其他时候,您可能需要在this中进行异步处理Function。在这种情况下,您应该使用thenCompose。您的返回类型Function应为CompletionStage。Function链中的下一个将获得该结果CompletionStage作为输入,从而展开CompletionStage。
// addOneAsync may be implemented by using another thread, or calling a remote method
abstract CompletableFuture<Integer> addOneAsync(int input);
CompletableFuture.completedFuture(1)
.thenCompose((x)->addOneAsync(x)) // doing something asynchronous, returns CompletableFuture<Integer>
.thenApply((y)->System.println(y)); // y is an Integer, the result of CompletableFuture<Integer> above
这与Javascript的想法类似Promise。Promise.then可以接受返回值或值a Promise的函数。这两种方法在Java中具有不同名称的原因是由于通用擦除。Function<? super T,? extends U> fn并且Function<? super T,? extends CompletionStage<U>> fn被视为相同的运行时类型- Function。因此thenApply,thenCompose必须明确命名,否则Java编译器会抱怨相同的方法签名。最终的结果是,Javascript的Promise.then实现分为两部分- thenApply和thenCompose-在Java中。
如果您也对相关功能感到困惑,可以阅读我的其他答案thenApplyAsync。
map,并flatMap在Stream?thenApply是map和thenCompose是flatMap的CompletableFuture。您通常thenCompose避免使用CompletableFuture<CompletableFuture<..>>。