在iOS 13的Combine框架中,共有三种collect
运算符方法。前两个很明显,但第三个使用了我无法弄清楚的类型。
collect(_:options:)
https://developer.apple.com/documentation/foundation/timer/timerpublisher/3329497-collect
func collect<S>(_ strategy: Publishers.TimeGroupingStrategy<S>,
options: S.SchedulerOptions? = nil)
-> Publishers.CollectByTime<Timer.TimerPublisher, S>
where S : Scheduler
谁能举例说明如何调用此方法?
最佳答案
经过一番努力,我想出了一个这样的例子:
let t = Timer.publish(every: 0.4, on: .main, in: .default)
t
.scan(0) {prev,_ in prev+1}
.collect(.byTime(DispatchQueue.main, .seconds(1))) // *
.sink(receiveCompletion: {print($0)}) {print($0)}.store(in:&storage)
let cancellable = t.connect()
delay(3) { cancellable.cancel() }
(其中 storage
是通常的 Set<AnyCancellable>
以保持订阅者处于事件状态)。
输出为:
[1, 2]
[3, 4, 5]
[6, 7]
因此,我们大约每 0.4 秒发布一个新数字,但是 collect
每 1 秒才执行一次操作。因此,前两个值到达,发布 1
和2
,然后 collect
完成它的工作,累积到目前为止到达的所有值,并将它们作为数组发布,[1,2]
。等等。每一秒,到目前为止,管道中出现的任何内容都会累积到一个数组中并作为数组发布。
关于ios - 结合框架第三个 `collect`方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330610/