CompletableFuture链接结果

plz*_*lme 6 java java-8 completable-future

我试图将方法的调用/结果链接到下一个调用.我得到编译时错误方法E因为如果无法从前一次调用获得objB的引用.

如何将上次调用的结果传递给下一个链?我完全误解了这个过程吗?

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();
Run Code Online (Sandbox Code Playgroud)

Mis*_*sha 8

您可以将中间存储CompletableFuture在变量中,然后使用thenCombine:

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

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

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

objC = futureC.join();
Run Code Online (Sandbox Code Playgroud)


Jos*_*ano 7

您应该使用thenCompose(异步映射),而不是thenApply(同步映射)。这是链接两个未来返回函数的示例:

public CompletableFuture<String> getStringAsync() {
    return this.getIntegerAsync().thenCompose(intValue -> {
        return this.getStringAsync(intValue);
    });
}

public CompletableFuture<Integer> getIntegerAsync() {
    return CompletableFuture.completedFuture(Integer.valueOf(1));
}

public CompletableFuture<String> getStringAsync(Integer intValue) {
    return CompletableFuture.completedFuture(String.valueOf(intValue));
}
Run Code Online (Sandbox Code Playgroud)

使用thenApply你不会返回未来。使用thenCompose,您就可以了。