Swift 快速合并:合并多个发布服务器并在其中任何一个发布服务器发出“true”时发出“true”`
我正在尝试构建一个发布服务器,当其他5个发布服务器中的任何一个发布true时,该发布服务器将发布true。我已经成功地构建了一个工作版本,但它感觉非常讨厌,使用CombineTest4+CombineTest,尤其是所有的Swift 快速合并:合并多个发布服务器并在其中任何一个发布服务器发出“true”时发出“true”`,swift,combine,Swift,Combine,我正在尝试构建一个发布服务器,当其他5个发布服务器中的任何一个发布true时,该发布服务器将发布true。我已经成功地构建了一个工作版本,但它感觉非常讨厌,使用CombineTest4+CombineTest,尤其是所有的$0.0 | | |$0.1 | | |$0.2 | |$0.3代码 我尝试过Merge5,但它只是返回上一个似乎设置的值 导入基础 进口联合收割机 课堂测试{ @发布的var one=false @发布变量2=错误 @发布变量3=错误 @发布变量4=错误 @发布变量5=错误
$0.0 | | |$0.1 | | |$0.2 | |$0.3
代码
我尝试过Merge5,但它只是返回上一个似乎设置的值
<代码>导入基础
进口联合收割机
课堂测试{
@发布的var one=false
@发布变量2=错误
@发布变量3=错误
@发布变量4=错误
@发布变量5=错误
}
let test=test()
var anyTrue=publisher.combinelatetest4(测试$1,测试$2,测试$3,测试$4)
.map{$0.0 | |$0.1 | |$0.2 | |$0.3}
.组合测试(测试$5)
.map{$0.0 | |$0.1}
真的吗{
印刷品(0美元)
}
测试3=正确
测试1=错误
是否有一种更简洁、重复性更低的方法来实现这一点?我已经编写了这个定制的variadic
combinelateest
函数,它组合了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() }
)
}
我不得不读了几遍才明白这段代码,哈哈,但它似乎非常适合我的用例!
let anyTrue = combineLatestN(
identity: false,
reductionFunction: { $0 || $1 },
publishers: test.$one, test.$two, test.$three, test.$four, test.$five)