CompletableFuture链接结果

时间:2016-05-17 00:29:06

标签: 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();

2 个答案:

答案 0 :(得分:7)

您可以将中间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();

答案 1 :(得分:1)

您应该使用 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));
}

使用 thenApply 不会返回未来。使用 thenCompose ,您可以做到。

相关问题