Reputation: 523
I am looking for suggestion about chaining multiple methods which are CompletableFutures.
Let's say I need to do 3 operations.
Hypothetically my methods are something like this:
public static CompletableFuture<Long> searchMaster() {
return CompletableFuture.supplyAsync (() -> 100L);
}
public static CompletableFuture<Long> insertIntoMaster() {
return CompletableFuture.supplyAsync (() -> 200L);
}
public static CompletableFuture<Long> insertIntoChildDB() {
return CompletableFuture.supplyAsync (() -> 300L);
}
Now my requirement is:
first method returns an id. I will pass that id to the second method. On successful result from second method, which will return a CompletableFuture, this primaryid will be passed on to the third method, which will insert some data in the child table.
How do I do the chaining with JDK8 CompletableFutures.
Upvotes: 3
Views: 2055
Reputation: 361555
Use one of the thenCompose() methods, which flatten futures much like Stream.flatMap() flattens streams:
CompletableFuture<Long> future = searchMaster()
.thenCompose(id -> insertIntoMaster(id))
.thenCompose(primaryId -> insertIntoChildDB(primaryId));
Upvotes: 2