CompletableFuture链接结果

CompletableFuture链接结果

本文介绍了CompletableFuture链接结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将方法的调用/结果链接到下一个调用.我得到了编译时错误methodE,因为如果无法从上一次调用中获取objB的引用,则会收到该错误.

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

推荐答案

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

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

这篇关于CompletableFuture链接结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:55