我写了这个自定义变量combineLatest
结合了N个发布者的函数。希望这是您所需要的:
func combineLatestN<P, T, E>(identity: T, reductionFunction: @escaping (T, T) -> T, publishers: P...) -> AnyPublisher<T, E>
where P: Publisher, P.Output == T, P.Failure == E {
publishers.reduce(
Publishers.Sequence<[T], E>(sequence: [identity]).eraseToAnyPublisher(),
{ $0.combineLatest($1).map(reductionFunction).eraseToAnyPublisher() }
)
}
困难的部分是弄清楚这个人的身份reduce
应该。什么出版社x
满足x.combineLatest(y).map(f) == y
对全部y
?一种解决方案x
将是一个发布身份的发布者f
once.
Usage:
let anyTrue = combineLatestN(
identity: false,
reductionFunction: { $0 || $1 },
publishers: test.$one, test.$two, test.$three, test.$four, test.$five)