Real-World Example: Combining API Responses
You'll learn how to build a practical example that fetches data from two independent API services and merges their responses using thenCombine.
The Scenario
Imagine you're building a dashboard that displays user information. You need to fetch a user's profile from one service and their recent activity from another service. These APIs are independent and can be called in parallel—perfect for thenCombine.
The Implementation
import java.util.concurrent.CompletableFuture;
class UserProfile {
String name;
String email;
UserProfile(String name, String email) {
this.name = name;
this.email = email;
}
}
class UserActivity {
int loginCount;
String lastLogin;
UserActivity(int loginCount, String lastLogin) {
this.loginCount = loginCount;
this.lastLogin = lastLogin;
}
}
class DashboardData {
UserProfile profile;
UserActivity activity;
DashboardData(UserProfile profile, UserActivity activity) {
this.profile = profile;
this.activity = activity;
}
}
public class ApiExample {
// Simulating API calls
static CompletableFuture<UserProfile> fetchUserProfile(String userId) {
return CompletableFuture.supplyAsync(() -> {
// Simulated network delay
try { Thread.sleep(500); } catch (InterruptedException e) {}
return new UserProfile("Alice", "alice@example.com");
});
}
static CompletableFuture<UserActivity> fetchUserActivity(String userId) {
return CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(300); } catch (InterruptedException e) {}
return new UserActivity(42, "2024-01-15");
});
}
public static void main(String[] args) {
String userId = "12345";
CompletableFuture<DashboardData> dashboard =
fetchUserProfile(userId).thenCombine(
fetchUserActivity(userId),
(profile, activity) -> new DashboardData(profile, activity)
);
dashboard.thenAccept(data -> {
System.out.println("User: " + data.profile.name);
System.out.println("Email: " + data.profile.email);
System.out.println("Logins: " + data.activity.loginCount);
System.out.println("Last Login: " + data.activity.lastLogin);
}).join();
}
}
Both API calls execute in parallel, completing in roughly 500ms total instead of 800ms sequentially. The thenCombine method waits for both, then merges them into a unified DashboardData object.
Key Takeaway: thenCombine enables efficient parallel API fetching patterns where independent data sources can be called simultaneously and merged into a single cohesive result.