Skip to main content
CompletableFuture · Topic 3 of 6

thenCompose and thenCombine

Definition​

thenCompose chains a step that itself returns a CompletableFuture, so the second call depends on the first result. thenCombine joins two independent futures that run at the same time, once both are done.

Example code​

A dependent call, and two independent calls combined

import java.util.concurrent.CompletableFuture;

class Demo {
static CompletableFuture<Integer> userId(String name) { return CompletableFuture.supplyAsync(() -> name.length()); }
static CompletableFuture<String> orders(int id) { return CompletableFuture.supplyAsync(() -> id + " orders"); }
static CompletableFuture<Integer> price() { return CompletableFuture.supplyAsync(() -> 120); }
static CompletableFuture<Integer> shipping() { return CompletableFuture.supplyAsync(() -> 30); }

public static void main(String[] args) {
// thenCompose: the second call needs the first result
String result = userId("Asha").thenCompose(Demo::orders).join();
System.out.println(result);

// thenCombine: two independent calls running at the same time
int total = price().thenCombine(shipping(), Integer::sum).join();
System.out.println(total);
}
}

// Output:
// 4 orders
// 150

Finished this page? Track your progress (saved only in your browser).