[英]How to use the result of a thenCompose multiple times in Java 8?
I have a series of thenCompose
calls, similar to我有一系列
thenCompose
调用,类似于
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenCompose(id -> getProfile(id))
.thenCompose(userProfile -> updateSomething(userProfile))
.thenCompose(__ -> notifyUser(id))
.thenAccept(__ -> doSomething())
.exceptionally(t -> doSomethingElse());
The getUserID
call returns a CompletionStage<String>
which I use in the next call for getProfile
. getUserID
调用返回一个CompletionStage<String>
,我在下一次调用getProfile
。 I need the same id
again for the notifyUser
call.对于
notifyUser
调用,我再次需要相同的id
。 How to make it available there?如何让它在那里可用? The IDE is showing
IDE 显示
Cannot resolve symbol id.
无法解析符号 ID。
The issue with your current code is that by the time you reach .thenCompose(__ -> notifyUser(id))
, the variable id
is not in scope anymore.您当前代码的问题在于,当您到达
.thenCompose(__ -> notifyUser(id))
,变量id
不再在范围内。
A simple solution in this case would be to invoke multiple thenCompose
directly on the CompletionStage
returned by getProfile
:在这种情况下,一个简单的解决方案是直接在
getProfile
返回的CompletionStage
上调用多个thenCompose
:
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenCompose(id ->
getProfile(id)
.thenCompose(userProfile -> updateSomething(userProfile))
.thenCompose(__ -> notifyUser(id))
)
// rest of chain calls
I think, your code becomes simpler, if you don't insist on using thenCompose
for every step:我认为,如果您不坚持在每一步都使用
thenCompose
,您的代码会变thenCompose
简单:
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenAccept(id -> {
updateSomething(getProfile(id).join());
notifyUser(id);
})
.thenRun(() -> doSomething())
.exceptionally(t -> doSomethingElse());
If having each step effectively sequential is your requirement, you can simply use join
:如果您要求每个步骤有效地按顺序进行,则可以简单地使用
join
:
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenAccept(id -> {
updateSomething(getProfile(id).join()).join();
notifyUser(id).join();
})
.thenRun(() -> doSomething())
.exceptionally(t -> doSomethingElse());
Considering that the whole chain is effectively sequential, you may just write it straight-forward:考虑到整个链实际上是连续的,您可以直接编写它:
myObject.updateDB(payload)
.thenRun(() -> {
YourUserIDType id = getUserID(payload.ID()).join();
updateSomething(getProfile(id).join()).join();
notifyUser(id).join();
doSomething();
})
.exceptionally(t -> doSomethingElse());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.