我正在尝试找到一种根据特定条件跳过 CompletableFuture 的方法。
例如
public CompletableFuture<Void> delete(Long id) {
CompletableFuture<T> preFetchCf = get(id);
CompletableFuture<Boolean> cf1 = execute();
/*This is where I want different execution path, if result of this future is true go further, else do not*/
// Execute this only if result of cf1 is true
CompletableFuture<T> deleteCf = _delete(id);
// Execute this only if result of cf1 is true
CompletableFuture<T> postDeleteProcess = postDelete(id);
}
实现这一目标的好方法是什么?
最佳答案
我将准备一个与您在问题中使用的示例不同的示例,因为从读者的角度来看,您的代码的意图并不十分清楚。
首先假设存在 CompletableFuture<String>
提供星球大战角色的名称。
CompletableFuture<String> character = CompletableFuture.completedFuture("Luke");
现在,假设我还有另外两个 CompletableFuture
代表我可能想要遵循的不同路径,具体取决于第一个可完成的 future 是否提供了绝地武士角色。
Supplier<CompletableFuture<String>> thunk1 = () -> CompletableFuture.completedFuture("This guy is a Jedi");
Supplier<CompletableFuture<String>> thunk2 = () -> CompletableFuture.completedFuture("This guy is not a Jedi");
请注意,我包装了 CompletableFuture
在一个Supplier
,以避免它们被急切地评估(这是称为 thunk 的概念)。
现在,我转到我的异步链:
character.thenApply(c -> isJedi(c))
.thenCompose(isJedi -> isJedi ? thunk1.get() : thunk2.get())
.whenComplete((answer, error) -> System.out.println(answer));
使用thenCompose
让我根据 boolean 结果选择一条路径。在那里,我评估了其中一个 thunk 并使其创建一个新的 CompletableFuture
为了我在乎的路。
这将打印到屏幕上 "This guys is a Jedi"
.
所以,我相信您正在寻找的是 thenCompose
方法。
关于Java短路CompletableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48588002/