Richard Yu
Richard Yu

Reputation: 11

Passing a CompletableFuture's result to another

I am relatively inexperienced with Java's CompletableFuture and I probably need some help with it. Here is what I am trying to do.

/* I want to use the result of the future in a second one.
 * So basically, what I want to do is to return the second future,
 * but I don't want to block and wait for the first future to complete.
 * /
CompletableFuture<TypeA> -> CompletableFuture<TypeB> 

So I am wondering if there is a way to 'chain' the first future to the second one such that one single future(TypeB) will be returned.

Upvotes: 1

Views: 2081

Answers (2)

Benjamin Peter
Benjamin Peter

Reputation: 4038

We had a similar problem when trying to write test code and the future that has to be tested is created in a background thread so we cannot simply chain it with the outer future that we want to use for asserting.

My colleague created the following method.

static <U> void propagateResultWhenCompleted(
    final CompletionStage<U> source,
    final CompletableFuture<U> target)
{
    source.whenComplete((r, t) -> complete(target, r, t));
}

I wonder why this is not in the standard tool set. Surely it is not the idiomatic way of using futures but it is handy for some occasions.

Upvotes: 0

Kartik
Kartik

Reputation: 7917

The thenCompose method does exactly that.

Here is an example at https://www.baeldung.com/java-completablefuture:

CompletableFuture<String> completableFuture 
  = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));

assertEquals("Hello World", completableFuture.get());

Also have a look at the difference between thenCompose and thenComposeAsync.

Upvotes: 3

Related Questions