4

我有一个使用接口CompletionStage的框架,我很好奇为什么在CompletableFuture中定义了辅助方法anyOfallOf发现。

似乎他们应该在接口而不是实现上操作?

到目前为止,我对 CompletionStage 界面非常不满意。是否有其他 Java 库兼容 CompletionStage 但有人可以推荐不同的超集接口?

或者也许是一些用额外的辅助方法编写的库来使用 CompletionStage ?

4

2 回答 2

3

如果您想要的只是一种为type 对象提供相同功能的方法anyOf,您可以简单地求助于:allOfCompletionStagetoCompletableFuture

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));
}
于 2016-02-22T19:52:04.640 回答
1

这是我想出的

/**
 * 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;
    }

}
于 2016-02-22T18:28:08.707 回答