Java – completable future | then apply vs thenpose

I can't let my head revolve around the difference between thenapply () and thenpose ()

So can anyone provide an effective use case?

From a Java document:

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

I get the second parameter of thencomponent, which extends completionstage, and then the application will not

Someone can provide an example, in which case I have to use and then apply when thenpose?

Solution

So if you have a synchronous mapping function, apply it

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

If you have an asynchronous mapping function (that is, a function that returns a completable future), use this function Then it will return the result directly, not nested in the future

CompletableFuture<Integer> future = 
    CompletableFuture.supplyAsync(() -> 1)
                     .thenCompose(x -> CompletableFuture.supplyAsync(() -> x+1));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>