What is the practical difference between thenApply and thenCompose in CompletableFuture?
Options
- There is no difference at all, both are the same method
thenApplymaps a result;thenComposeflattens futures (Correct option)thenComposeblocks the thread;thenApplydoes notthenApplyhandles the errors;thenComposedoes not
Answer
thenApply transforms the result with a normal function; thenCompose is for a function that itself returns a CompletableFuture and flattens it (like flatMap)
Why
A CompletableFuture<T> represents a result that will exist later, without blocking while you wait.
thenApply(f): when the result arrives, apply a plain function T -> U and get a CompletableFuture<U>.
thenCompose(f): use when f itself returns a CompletableFuture<U> (for example, another async call). Without it you would get a nested CompletableFuture<CompletableFuture<U>>.
It is the same idea as map vs flatMap.
CompletableFuture<Order> order =
findUserAsync(id) // CF<User>
.thenCompose(u -> findOrderAsync(u)) // CF<Order>
.thenApply(o -> o.withTax());Remember
thenApply = map. thenCompose = flatMap.