CompletableFuture chaining results

前端 未结 2 1268
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 07:17

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 previou

相关标签:
2条回答
  • 2021-01-12 07:45

    You should use thenCompose, which is an asynchronous mapping, as opposed to thenApply, which is synchronous. Here's an example that chains two future-returning functions:

    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));
    }
    

    With thenApply you don't return a future. With thenCompose, you do.

    0 讨论(0)
  • 2021-01-12 08:03

    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();
    
    0 讨论(0)
提交回复
热议问题