如何在 Combine 中对任意数量的 Bool Publisher 执行 "all" 操作?

How to perform an "all" operation on an arbitrary number of Bool Publishers in Combine?

我遇到这样一种情况,我试图确定任意数量的布尔检查(用户定义的条件)是否为 true。这似乎是 CombineLatest 与 AllSatisfy 相结合的工作......问题在于 CombineLatest 仅支持固定数量的元素(2、3 或 4)。除了使用重复的 2 元素 CombineLatest 发布者将每个结果与另一个发布者组合之外,还有其他模式吗?

理想情况下,我想要以下内容:

Publishers.CombineLatestMany(arrayOfPublishers).allSatisfy { ... }

而不是:

Publishers.CombineLatest(pubA, pubB).combineLatest(pubC).combineLatest(pubD) ...

这应该可以解决您的需求,除非您的发布商属于不同类型:

extension Publisher where Output == Bool {
    func and<P: Publisher>(_ rest: P...) -> some Publisher where P.Output == Output, P.Failure == Failure {
        rest.reduce(AnyPublisher(self)) { acc, next in
            AnyPublisher(acc.combineLatest(next).map { [=10=] &&  })
        }
    }
}