我尝试在 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/