Basic thenCompose Syntax and Usage
You'll learn: How to write your first thenCompose call to chain two async operations where the second depends on the first's result.
The Core Mechanic
thenCompose is like a handoff in a relay race where the second runner needs something from the first runner before they can start their own race. You use it when your transformation function doesn't just return a simple value—it returns another CompletableFuture.
Think of it this way: if thenApply unwraps a gift and puts a bow on it, thenCompose unwraps a gift that contains instructions to find another gift.
Basic Syntax
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<String> result = future1.thenCompose(number ->
CompletableFuture.supplyAsync(() -> "Result: " + (number * 2))
);
What's happening:
future1produces5thenComposereceives5and passes it to your lambda- Your lambda returns a new CompletableFuture that does another async operation
thenComposeflattens this, soresultisCompletableFuture<String>, notCompletableFuture<CompletableFuture<String>>
Real-World Pattern
CompletableFuture<Integer> userId = CompletableFuture.supplyAsync(() -> 42);
CompletableFuture<String> userName = userId.thenCompose(id ->
CompletableFuture.supplyAsync(() -> "User_" + id) // Simulates DB lookup
);
System.out.println(userName.join()); // "User_42"
The second operation depends on the first's result and is itself asynchronous.
Key Takeaway:
Use thenCompose when your transformation returns another CompletableFuture—it flattens nested futures and chains dependent async operations into a single pipeline.