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

时间:2018-08-03 16:56:27

标签: 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窗口中?也许重要的是,两个变量的类型都不同。

也许不可能,我必须使用其他方法吗?我不知道...

1 个答案:

答案 0 :(得分:0)

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

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和提供{ {1}}(也取决于homeOfHuman)。