CompletionStage chaining when 2nd stage is not interested in the 1st stage result value

杀马特。学长 韩版系。学妹 提交于 2020-07-18 08:22:44

问题


Scenario:

  • there are two stages
  • 2nd stage is to be executed only after the 1st one is completed
  • 2nd stage is not interested in the 1st stage result but merely in the fact that the first stage is completed

Consider the existing method:

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

It doesn't quite satisfy my needs cause the function is aware of the 1st stage result value ? super T

What I would rather like to have is something like:

public <U> CompletionStage<U> thenApply(Supplier<? extends U> fn);

Question: do I understand correctly that there's no out-of-the-box solution for that so I will have to write my own wrapper function in order to achieve the desired behavior?


回答1:


There is no such built-in solution. But you could "abuse" CompletableFuture.supplyAsync and thenCompose:

Supplier<String> sup = ()->"s";
CompletableFuture.supplyAsync(()->4)
        .thenCompose(x->CompletableFuture.supplyAsync(sup))
        .thenAccept(System.out::println);

BTW, I guess probably there are no such convenience methods because CompletionStage/CompletableFuture already have quite many methods.




回答2:


If the thing you want to run is not expected to return a result, you can use thenRun:

CompletableFuture<Thing> thingsFuture = CompletableFuture.supplyAsync(() -> getThings());
thingsFuture.thenRun(() -> System.out.println("Got ALL THE THINGS!"));

If you need it to return a result, then I'm afraid you're out of luck. Best option you have is just to ignore the argument in your lambda.



来源:https://stackoverflow.com/questions/40410845/completionstage-chaining-when-2nd-stage-is-not-interested-in-the-1st-stage-resul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!