Course contentsShow
← Java
Lesson 2823 of 2,87051. CompletableFutureFree lesson

Combining thenCompose with thenApply and thenAccept

Build complex async pipelines that mix thenCompose for async chaining with thenApply for transformations.

Combining thenCompose with thenApply and thenAccept

You'll learn how to build sophisticated async pipelines by combining thenCompose for chaining async operations with thenApply for transformations and thenAccept for final consumption.

The Core Idea

Now that you know thenCompose chains async operations, thenApply transforms results synchronously, and thenAccept consumes results without returning values, you can mix them strategically in a single pipeline. This creates powerful async workflows: fetch data asynchronously, transform it, trigger another async operation, transform again, and finally consume.

Think of it like a recipe: thenCompose lets you wait for water to boil (async), thenApply lets you add seasoning (quick transform), and thenAccept lets you serve the dish (final action).

Building Complex Pipelines

Here's a realistic pattern combining all three:

CompletableFuture.supplyAsync(() -> fetchUserId())
    .thenCompose(userId -> fetchUserProfile(userId))  // async DB call
    .thenApply(profile -> profile.toUpperCase())      // sync transform
    .thenCompose(name -> sendNotification(name))      // async API call
    .thenApply(response -> response.getStatusCode())  // extract status
    .thenAccept(status -> System.out.println("Status: " + status));

The pipeline flows naturally: fetch ID → fetch profile (wait) → uppercase (instant) → send notification (wait) → extract code (instant) → print (consume).

Strategic Placement

  • Use thenCompose when the next step returns a CompletableFuture
  • Use thenApply when you need quick, synchronous transformations
  • Use thenAccept at the end for side effects like logging or UI updates

Each method passes its result to the next stage, creating a clean, non-blocking pipeline that reads like a story.

Key Takeaway: Combine thenCompose for async chaining, thenApply for transformations, and thenAccept for final consumption to build expressive, multi-stage async pipelines that remain readable and maintainable.