下面是一个去抖动示例:
半秒内的数据将被丢弃。
let bounces:[(Int,TimeInterval)] = [
(0, 0),
(1, 0.25), // 0.25s interval since last index
(2, 1), // 0.75s interval since last index
(3, 1.25), // 0.25s interval since last index
(4, 1.5), // 0.25s interval since last index
(5, 2) // 0.5s interval since last index
]
let subject = PassthroughSubject<Int, Never>()
cancellable = subject
.debounce(for: .seconds(0.5), scheduler: RunLoop.main)
.sink { index in
print ("Received index \(index)")
}
for bounce in bounces {
DispatchQueue.main.asyncAfter(deadline: .now() + bounce.1) {
subject.send(bounce.0)
}
}
// Prints:
// Received index 1
// Received index 4
// Received index 5
字符串
但我想把这些丢弃的数据结合起来,我的预期结果是:
// Prints:
// Received index [0, 1]
// Received index [2, 3, 4]
// Received index [5]
型
有什么帮助吗?
3条答案
按热度按时间oknrviil1#
您可以使用
scan
将发出的值累积到一个数组中,技巧是在debounce发出该数组后重置该数组:字符串
但是,这种方法有两个缺陷:
handleEvents
不太“典型”。不过,您可以将不太好的逻辑 Package 到它自己的发布者中,并且更加习惯:
型
,并像这样使用它:
型
lskq00tm2#
您不应该使用
debounce
,因为它是一个过滤操作。相反,使用collect
的重载,它接受一个TimeGroupingStrategy
-collect
* 收集 * 所有来自上游的元素到数组中。字符串
ojsjcaue3#
实现这个目标的正确方法是为发布者编写一个自定义操作符,它将对输入值进行反跳,并在所需的延迟之后将它们作为数组传递给下游。我在我的项目中使用它,它工作得很好:
字符串
并将其用作出版商的操作员:
型