我目前正在尝试实现两个出版商的合并。但是我找不到适合我的用例的解决方案。
我想合并 2 个发布者,它们都发出相同类型的结构数组。我希望合并的发布者在任一合并的发布者发出新值时发出值。
基本上这将是 Publishers.CombineLatest
的用例,但由于我的底层发布者都发出相同类型的值 merge
这里会更合适。但是Publishers.Merge
不会记住合并发布者的最后一个值。
因此我想要一个 Publishers.CombineLatest
Publishers.Merge
的行为手术。组合框架内是否有可以完成这种行为的东西?
应该发生什么的粗略示例:
Definitions:
PublisherA: emits -> [Value]
PublisherB emits -> [Value]
CombinedAB: -> [Value]
PublisherA changes: CombinedAB -> [NewA, OldB]
PublisherB changes: CombinedAB -> [OldA, NewB]
let a = CurrentValueSubject<[Int], Never>(["a", "b", "c"])
let b = CurrentValueSubject<[Int], Never>(["d", "e", "f"])
let combined = Publisher.AnyThing(a, b)
combined.sink {
print($0)
}
b.send(["g", "h", "i"])
Outputs:
["a", "b", "c", "d", "e", "f"]
["a", "b", "c", "g", "h", "i"]
所以它基本上是一个
Publishers.CombineLatest
但没有发出 (NewA,OldB) 元组,而是已经合并,因为两个值具有相同的类型。任何帮助深表感谢。
最佳答案
假设您的组合操作只是您可以执行的子数组的连接:
let a = CurrentValueSubject<[String], Never>(["a", "b", "c"])
let b = CurrentValueSubject<[String], Never>(["d", "e", "f"])
let combined = Publishers.CombineLatest(a, b).map(+)
combined.sink {
print($0) //["a", "b", "c", "d", "e", "f"] and ["a", "b", "c", "g", "h", "i"]
}
b.send(["g", "h", "i"])
我不完全确定你所说的“已经合并”是什么意思。
如果你想让最新发出的数组总是在组合数组的末尾,那么你可能需要一个
scan
map(+)
之前的运算符能够与以前的排放量进行比较并交换它们。
关于swift - 合并 Publishers.Merge 但与 Publishers.combineLatest 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60149906/