CompletableFuture: Chaining
This lesson discusses how to chain Completable Futures.
We'll cover the following
Until now, we have looked at how to create a CompletableFuture
and how to add callbacks.
One more interesting thing that we can do is combine CompletableFuture instances in a chain of computation steps. Suppose we want to get some data from a service and save it to the database. We can write two CompletableFuture instances and chain them together. The first instance will complete and share its result to the second instance.
There are two methods which help us achieve this. The first one is thenCompose()
, and the second one is thenCombine()
. We will look at each one of them below.
1) thenCompose()
The thenCompose()
method takes a Function<? super T,? extends CompletionStage<U>>
as input, i.e., it takes a function that has the result of previous computation as input and returns a CompletableFuture
as the output.
Below is an example of thenCompose()
. This is the same example that we used for thenApply()
. Now, you might be wondering what the difference between thenCompose()
and thenApply()
is. Why do we need to use thenCompose()
when we can use thenApply()
?
The problem in using thenApply()
is that, if we use theApply()
in the below example, the result will be nested in CompletableFuture, i.e., CompletableFuture<CompletableFuture<Integer>>
.
We should always use thenCompose()
if you need a flat result.
Get hands-on with 1400+ tech skills courses.