我有一个使用接口CompletionStage的框架,我很好奇为什么在CompletableFuture中定义了辅助方法anyOf
或allOf
发现。
似乎他们应该在接口而不是实现上操作?
到目前为止,我对 CompletionStage 界面非常不满意。是否有其他 Java 库兼容 CompletionStage 但有人可以推荐不同的超集接口?
或者也许是一些用额外的辅助方法编写的库来使用 CompletionStage ?
我有一个使用接口CompletionStage的框架,我很好奇为什么在CompletableFuture中定义了辅助方法anyOf
或allOf
发现。
似乎他们应该在接口而不是实现上操作?
到目前为止,我对 CompletionStage 界面非常不满意。是否有其他 Java 库兼容 CompletionStage 但有人可以推荐不同的超集接口?
或者也许是一些用额外的辅助方法编写的库来使用 CompletionStage ?
如果您想要的只是一种为type 对象提供相同功能的方法anyOf
,您可以简单地求助于:allOf
CompletionStage
toCompletableFuture
public static CompletionStage<Object> anyOf(CompletionStage<?>... css) {
return CompletableFuture.anyOf(Arrays.stream(css)
.map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
public static CompletionStage<Void> allOf(CompletionStage<?>... css) {
return CompletableFuture.allOf(Arrays.stream(css)
.map(CompletionStage::toCompletableFuture).toArray(CompletableFuture[]::new));
}
这是我想出的
/**
* A class with several helper methods for working with {@link CompletionStage}
*/
public class CompletionStages {
public static CompletionStage<Object> anyOf(CompletionStage... completionStages) {
if (completionStages == null) {
throw new IllegalArgumentException("You must pass a non-null argument for completionStages");
}
if (completionStages.length == 0) {
throw new IllegalArgumentException("You must pass a non-empty argument for completionStages");
}
CompletableFuture result = new CompletableFuture();
for(CompletionStage completionStage : completionStages) {
completionStage.thenAccept( r -> result.complete(r));
}
return result;
}
public static CompletionStage<Void> allOf(CompletionStage... completionStages) {
if (completionStages == null) {
throw new IllegalArgumentException("You must pass a non-null argument for completionStages");
}
if (completionStages.length == 0) {
throw new IllegalArgumentException("You must pass a non-empty argument for completionStages");
}
CompletionStage result = CompletableFuture.completedFuture(null);
for(int i = 0; i < completionStages.length; i++) {
CompletionStage curr = completionStages[i];
result = result.thenAcceptBoth(curr, (o, o2) -> {});
}
return result;
}
}