CompletableFuture | thenApply vs thenCompose

前端 未结 5 1003
离开以前
离开以前 2020-12-12 12:13

I can\'t get my head around the difference between thenApply() and thenCompose().

So, could someone provide a valid use case?

Fro

5条回答
  •  难免孤独
    2020-12-12 12:54

    The updated Javadocs in Java 9 will probably help understand it better:

    thenApply

    CompletionStage thenApply​(Function 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.

    This method is analogous to Optional.map and Stream.map.

    See the CompletionStage documentation for rules covering exceptional completion.

    thenCompose

     CompletionStage thenCompose​(Function> fn)
    

    Returns a new CompletionStage that is completed with the same value as the CompletionStage returned by the given function.

    When this stage completes normally, the given function is invoked with this stage's result as the argument, returning another CompletionStage. When that stage completes normally, the CompletionStage returned by this method is completed with the same value.

    To ensure progress, the supplied function must arrange eventual completion of its result.

    This method is analogous to Optional.flatMap and Stream.flatMap.

    See the CompletionStage documentation for rules covering exceptional completion.

提交回复
热议问题