How to use a method that returns CompletionStage inside thenCombineAsync

I have 3 functions that return a CompletionStage . Let's say that they look like this:

 CompletionStage<A> funcA(); CompletionStage<B> funcB(); CompletionStage<C> funcC(A a, B b); 

Now I would like to write fuction funcD , which returns a CompletionStage<C> . The result is calculated using funcC and params cames from both funcA and funcB . Now the question is how to do it right?

My attempts after reading the documentation look like this, but I'm not sure if this is the right use. The problem is that after thenCombineAsync I get CompletionStage<CompletionStage<C>> , and the last line looks like an ugly workaround to extract the correct result. Can this be done better?

 CompletionStage<C> funcD() { CompletionStage<B> completionStageB = funcB(); return funcA() .thenCombineAsync(completionStageB, (a,b) -> funcC(a,b)) .thenComposeAsync(result -> result); } 

Suppose method declarations cannot be modified.

+5
source share
1 answer

No thenComposeWithBoth . If you cannot change the method signatures, I would just leave it as it is (but delete Async - see below). The only way to make it shorter is: join() inside the Combine step:

 funcA() .thenCombineAsync(completionStageB, (a,b) -> funcC(a,b).join()); 

In a separate note, you use methods ...Async unnecessarily. Since your funcC returns a CompletableFuture , it probably doesn't work for long, and there is no need to schedule it asynchronously. And result -> result , of course, does not need to be run in a separate thread.

+3
source

Source: https://habr.com/ru/post/1265708/


All Articles