[英]How to use the result of a thenCompose multiple times in Java 8?
我有一系列thenCompose
调用,类似于
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenCompose(id -> getProfile(id))
.thenCompose(userProfile -> updateSomething(userProfile))
.thenCompose(__ -> notifyUser(id))
.thenAccept(__ -> doSomething())
.exceptionally(t -> doSomethingElse());
getUserID
调用返回一个CompletionStage<String>
,我在下一次调用getProfile
。 对于notifyUser
调用,我再次需要相同的id
。 如何让它在那里可用? IDE 显示
无法解析符号 ID。
您当前代码的问题在于,当您到达.thenCompose(__ -> notifyUser(id))
,变量id
不再在范围内。
在这种情况下,一个简单的解决方案是直接在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
我认为,如果您不坚持在每一步都使用thenCompose
,您的代码会变thenCompose
简单:
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenAccept(id -> {
updateSomething(getProfile(id).join());
notifyUser(id);
})
.thenRun(() -> doSomething())
.exceptionally(t -> doSomethingElse());
如果您要求每个步骤有效地按顺序进行,则可以简单地使用join
:
myObject.updateDB(payload)
.thenCompose(__ -> getUserID(payload.ID()))
.thenAccept(id -> {
updateSomething(getProfile(id).join()).join();
notifyUser(id).join();
})
.thenRun(() -> doSomething())
.exceptionally(t -> doSomethingElse());
考虑到整个链实际上是连续的,您可以直接编写它:
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.