java - 如何在最后访问多个 Completablefuture Stage 变量

标签 java lambda completable-future

我尝试在 completablefuture 管道的末尾使用多个不同的变量。很难解释。这是我的例子:

private void test(){
lib.getHumanFromDatabase().thenApplyAsync(human->{
        //returns one human from the database
        return human;
    }, executor).thenComposeAsync(humanFromDb-> {
        //Set new name of human
        humanFromDb.setName("NameOfHuman");
        //update human and return the new entity
        return lib.updateHumanInDatbase(humanFromDb);
    }, executor).thenComposeAsync(humanFromDb-> {
        //Then ask for his home
        return lib.getHomeOfHuman(humanFromDb);
    }).thenAcceptAsync(homeOfHuman-> {
        //So here at the end i want to access 
        //the variable humanFromDb AND
        //the variable homeOfHuman BUT
        //i only get homeOfHuman ...
    }, executor).handleAsync((ok, ex) -> {
        //Just for exception and so on
    }, executor);
}

我首先尝试将 lambda 之外的变量存储在方法内,但在这里我得到的信息是该变量必须是最终的。是否有可能访问这两个变量并最终返回它们,例如在某些 UI 窗口或其他东西中?也许重要的是,两个变量的类型不同。

也许这是不可能的,我必须使用不同的方法?我不知道...

最佳答案

当只有一个依赖链时,您可以使用单个方法链定义所有依赖阶段。否则,您必须在变量中存储一个或多个阶段,即

private void test() {    
    CompletableFuture<Human> humanFuture =
        lib.getHumanFromDatabase().thenApplyAsync(human -> {
            //returns one human from the database
            return human;
        }, executor).thenComposeAsync(humanFromDb -> {
            //Set new name of human
            humanFromDb.setName("NameOfHuman");
            //update human and return the new entity
            return lib.updateHumanInDatbase(humanFromDb);
        }, executor);

    humanFuture.thenComposeAsync(humanFromDb -> {
          //Then ask for his home
          return lib.getHomeOfHuman(humanFromDb);
      }).thenAcceptBothAsync(humanFuture, (humanFromDb, homeOfHuman) -> {
          //So here you can now access humanFromDb, homeOfHuman

      }, executor).handleAsync((ok, ex) -> {
          //Just for exception and so on

      }, executor);
}

因此,在这里,您只需要记住 humanFuture ,稍后将其传递给 thenAcceptBothAsync ,以创建一个依赖于 humanFuture 和提供 homeOfHuman 的 future(也依赖于 humanFuture )的 future 的阶段。

关于java - 如何在最后访问多个 Completablefuture Stage 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51677094/

相关文章:

java - 可完成的 future : Waiting for first one normally return?

java - 为什么 CompletableFuture 的 thenAccept() 没有在主线程上运行

java - 我如何以 struts 迭代器生成的单个表单调用多个操作

java - Selenium WebDriver Page 对象模型描述

python - 在小于 O(n) 的时间内找到小于给定数字的斐波那契和

amazon-web-services - AWS Lambda未与Dynamo Db连接

c# - 编译器如何知道 lambda 表达式应该是什么数据类型

java - 不存在类型变量 U 的实例,因此 Foo 符合 CompletionStage<U>

java - 使用 Selenium -Browserstack 设置 PAC 文件代理

java - 如何在 wildfly 中激活 JDBC 日志