结合框架第三种“收集”方法

时间:2019-12-13 22:33:06

标签: ios ios13 combine

在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

任何人都可以举一个例子说明如何调用此方法吗?

2 个答案:

答案 0 :(得分:1)

经过一番努力,我想到了一个这样的例子:

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秒钟发布一次。因此,前两个值到达,分别发布12,然后collect完成其工作,累加到目前为止已到达的所有值,并将它们发布为数组{ {1}}。等等。到目前为止,所有流经管道的东西都会每秒存储到一个数组中,并作为数组发布。

答案 1 :(得分:0)

在该枚举中发布了两种TimeGroupingStrategy机制。截至iOS 13.3为止,仍然只有两个:

  • byTime
  • byTimeOrCount

在任何一种情况下,前两个参数都是在其上运行它们的调度程序(Immediate,DispatchQueue,Runloop或OperationQueue),通常是通过传入的内容来推断的。与调度程序一起的是Stride-a您指定的时间间隔-操作员将缓冲值。

byTime中,它将按照指定的时间间隔收集和缓冲所接收的元素(使用无限制的内存量)。 byTimeOrCount将限制缓冲到特定计数的项目数。

指定它们的两种方法是:

let q = DispatchQueue(label: self.debugDescription)
publisher
    .collect(.byTime(q, 1.0))

let q = DispatchQueue(label: self.debugDescription)
publisher
    .collect(.byTimeOrCount(q, 1.0, 10))

这些使用DispatchQueue,但是您可以轻松地使用任何其他调度程序。 如果您仅跨步输入Double,它将以秒为单位。

在两种情况下,如果经过了时间(或计数,如果指定了该版本),则操作员将依次向其订阅者发布收集的值的数组。