问题描述
我正在尝试在completablefuture管道的末尾使用多个不同的变量.很难解释.这是我的示例:
Im trying to use multiple different variables at the end of a completablefuture pipe. Its hard to explain. Here is my example:
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窗口中?也许重要的是,两个变量的类型都不同.
I first tried to store the variables outside of lambda inside the method but here i get the information, that the variable has to be final. Is there any possebility to access both variables and the end to return them for example in some UI-Window or something? Maybe it is important, that both variables are of a different type.
也许不可能,我必须使用其他方法吗?我不知道...
Maybe it is not possible and i have to use a different approach? I have no clue ...
推荐答案
当只有单个依赖项链时,您可以使用单个方法链定义所有依赖阶段.否则,您必须将一个或多个阶段存储在一个变量中,即
You can define all dependent stages with a single method chain, when there is just a single chain of dependencies. Otherwise, you have to store one or more stages in a variable, i.e.
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 的阶段code>和提供
homeOfHuman
的未来(也取决于 humanFuture
).
So here, you just need to remember the humanFuture
, to pass it later on to thenAcceptBothAsync
to create a stage depending on both, the humanFuture
and the future which provides the homeOfHuman
(which also depends on humanFuture
).
这篇关于最后如何访问多个Completablefuture Stage变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!