我有一组发布者,我想等待它们,直到所有发布者都发出一个值,然后处理结果.
我try 使用collect()
和Publishers.MergeMany
(编辑:使用MergeMany
,因为我正在寻找一个可以扩展到40个或更多出版商的解决方案),但Collect只按收到结果的顺序收集结果,而不尊重值的顺序,从而正确地关联出版商和价值.
为了简化代码并说明问题,以下是Playround代码:
import Combine
var cancellables = [AnyCancellable]()
let stringPublishers = [
Just("1").delay(for: RunLoop.SchedulerTimeType.Stride(Double.random(in: 0.1...1.0)), scheduler: RunLoop.main),
Just("2").delay(for: RunLoop.SchedulerTimeType.Stride(Double.random(in: 0.1...1.0)), scheduler: RunLoop.main),
Just("3").delay(for: RunLoop.SchedulerTimeType.Stride(Double.random(in: 0.1...1.0)), scheduler: RunLoop.main),
Just("4").delay(for: RunLoop.SchedulerTimeType.Stride(Double.random(in: 0.1...1.0)), scheduler: RunLoop.main),
Just("5").delay(for: RunLoop.SchedulerTimeType.Stride(Double.random(in: 0.1...1.0)), scheduler: RunLoop.main)
]
Publishers.MergeMany(stringPublishers).collect().sink { value in
print(value)
}.store(in: &cancellables)
运行代码,结果通常是无序的,比如["2", "4", "5", "3", "1"]
、["1", "4", "5", "3", "2"]
等等.
我怎么才能总是得到["1", "2", "3", "4", "5"]
分呢?
我try 在这里修改solution,但遇到了问题,因为我的inputArray
已经是一个由Publishers
组成的数组,而不是整数值或字符串的普通值.