如何在 Combine 中使用 collect(.byTime) 或 collect(.byTimeOrCount)
How to use collect(.byTime) or collect(.byTimeOrCount) in Combine
publisher.collect(<#T##strategy: Publishers.TimeGroupingStrategy<Scheduler>##Publishers.TimeGroupingStrategy<Scheduler>#>)
我在任何地方都找不到任何例子,documentation is bland... free Using Combine 书中也没有什么有趣的东西。
在Xcode 11.3 中,补全效果不是很好,但格式并不太复杂。在 TimeGroupingStrategy 枚举中发布了两个选项(从 iOS 13.3 开始):
byTime
byTimeOrCount
当您指定其中一种策略时,您还需要指定它运行的调度程序,这是这些枚举案例的参数之一。
例如,要按时间收集,收集间隔为 1.0 秒,使用 DispatchQueue,您可以使用:
let q = DispatchQueue(label: self.debugDescription)
let cancellable = publisher
.collect(.byTime(q, 1.0))
byTime
版本将在上游发布者提供的缓冲值中指定的时间间隔内使用无限量的内存。
byTimeOrCount
需要一个额外的 count
参数,该参数在将缓冲集合发送给订阅者之前对收集的项目数设置上限。
例如,最大缓冲区大小为 10 项的相同代码:
let q = DispatchQueue(label: self.debugDescription)
let cancellable = publisher
.collect(.byTimeOrCount(q, 1.0, 10))
您可以在 Using Combine 项目中查看正在使用的代码的更多具体示例,以及验证它们如何运行的单元测试:
publisher.collect(<#T##strategy: Publishers.TimeGroupingStrategy<Scheduler>##Publishers.TimeGroupingStrategy<Scheduler>#>)
我在任何地方都找不到任何例子,documentation is bland... free Using Combine 书中也没有什么有趣的东西。
在Xcode 11.3 中,补全效果不是很好,但格式并不太复杂。在 TimeGroupingStrategy 枚举中发布了两个选项(从 iOS 13.3 开始):
byTime
byTimeOrCount
当您指定其中一种策略时,您还需要指定它运行的调度程序,这是这些枚举案例的参数之一。
例如,要按时间收集,收集间隔为 1.0 秒,使用 DispatchQueue,您可以使用:
let q = DispatchQueue(label: self.debugDescription)
let cancellable = publisher
.collect(.byTime(q, 1.0))
byTime
版本将在上游发布者提供的缓冲值中指定的时间间隔内使用无限量的内存。
byTimeOrCount
需要一个额外的 count
参数,该参数在将缓冲集合发送给订阅者之前对收集的项目数设置上限。
例如,最大缓冲区大小为 10 项的相同代码:
let q = DispatchQueue(label: self.debugDescription)
let cancellable = publisher
.collect(.byTimeOrCount(q, 1.0, 10))
您可以在 Using Combine 项目中查看正在使用的代码的更多具体示例,以及验证它们如何运行的单元测试: