CompletableFuture and async composition question 93 of 180 mid
What is the difference between thenApply and thenCompose?
thenComposeruns on a different thread- Correct:
thenApplymaps a value to a value;thenComposeflat-maps a value to another future, avoiding a nestedCompletableFuture<CompletableFuture<T>> thenApplyis asynchronous,thenComposeis not- They are the same
It is map versus flatMap. If your function returns a plain value, use thenApply. If it returns
another CompletableFuture, which is what any further async call gives you, thenApply wraps it and
you end up with CompletableFuture<CompletableFuture<User>>. thenCompose unwraps it for you.
cf.thenApply(id -> loadUser(id)); // CF<CF<User>> -- almost always a mistake
cf.thenCompose(id -> loadUser(id)); // CF<User>
thenCombine is the third member: two independent futures plus a BiFunction when you want both
results and neither depends on the other.
Quiz yourself on CompletableFuture and async composition Suggest a correction