I've the following working piece of code using CompleteableFuture
:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
thenApplyAsync( f2Output -> f3( f2Output ) );
Is it possible to run another future that receives f1Output
as an input?
Something like:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
someApiThatRuns( f1Output -> f4( f1Output ) ). // <--
thenApplyAsync( f2Output -> f3( f2Output ) );
If this simplifies things one can ignore the result returned by f4()
.
If you don't mind running f2
and f4
in sequence, the simplest is just to call both in your lambda:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync(() -> f1() ).
thenApplyAsync(f1Output -> { f4(f1Output); return f2(f1Output); } ).
thenApplyAsync(f2Output -> f3(f2Output));
If however you want to run f2
and f4
in parallel, you can just store the intermediate future in a variable:
CompletableFuture<SomeObject> f1Future = CompletableFuture.supplyAsync(() -> f1());
CompletableFuture<SomeObject> future = f1Future.
thenApplyAsync(f1Output -> f2(f1Output)).
thenApplyAsync(f2Output -> f3(f2Output));
f1Future.thenAcceptAsync(f1Output -> f4(f1Output));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With