CompletionStage chaining when 2nd stage is not int

2020-07-27 23:56发布

问题:

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.