CompletableFuture chaining results

plzdontkillme picture plzdontkillme · May 17, 2016 · Viewed 13.5k times · Source

I am trying to chain the calls/results of the methods to the next call. I get compile time error methodE because if am not able to get the reference of objB from the previous call.

How can I pass the result of the previous call to the next chain? Have I completely misunderstood the process?

Object objC = CompletableFuture.supplyAsync(() -> service.methodA(obj, width, height))
    .thenApply(objA -> {
    try {
        return service.methodB(objA);
    } catch (Exception e) {
        throw new CompletionException(e);
    }
})
   .thenApply(objA -> service.methodC(objA))
   .thenApply(objA -> {
   try {
       return service.methodD(objA); // this returns new objB how do I get it and pass to next chaining call 
       } catch (Exception e) {
           throw new CompletionException(e);
       }
    })
    .thenApply((objA, objB) -> {
       return service.methodE(objA, objB); // compilation error 
  })
 .get();

Answer

Misha picture Misha · May 17, 2016

You could store intermediate CompletableFuture in a variable and then use thenCombine:

CompletableFuture<ClassA> futureA = CompletableFuture.supplyAsync(...)
    .thenApply(...)
    .thenApply(...);

CompletableFuture<ClassB> futureB = futureA.thenApply(...);

CompletableFuture<ClassC> futureC = futureA.thenCombine(futureB, service::methodE);

objC = futureC.join();