[英]How to disregard events when other event is executed?
let's say you are observing a property that changes quite often, eg a queue that should be refilled when it is below a threshold? 假设您正在观察一个经常更改的属性,例如,当队列低于阈值时应重新填充的队列?
queue.rac_valuesForKeyPath("count", observer: self)
.toSignalProducer()
.filter({ (queueCount: AnyObject?) -> Bool in
let newQueueCount = queueCount as! Int
return newQueueCount < 10
})
.on(next: { _ in
// Refilling the queue asynchronously and takes 10 seconds
self.refillQueue(withItemCount: 20)
})
.start()
When the queue is empty, the next handler will be triggered and fills the queue. 当队列为空时,将触发下一个处理程序并填充队列。 While filling the queue, the SignalProducer sends a new next event because the count property changed to 1 – and another and another.
在填充队列时,SignalProducer发送一个新的下一个事件,因为count属性更改为1 –一个又一个。 But I do not want the next handler to be triggered.
但是我不希望触发下一个处理程序。 Instead, I'd like it trigger once everytime the queue falls below that threshold.
相反,我希望每次队列低于该阈值时触发一次。
How can I do this in the best way? 我怎样才能最好地做到这一点? Are there any helpful event stream operations?
是否有任何有用的事件流操作? Any ideas?
有任何想法吗?
Cheers, 干杯,
Gerardo 杰拉多
I think you can use combinePrevios
operator here, as it gives you the present and the previous value: 我认为您可以在此处使用
combinePrevios
运算符,因为它可以为您提供当前值和以前的值:
queue.rac_valuesForKeyPath("count", observer: self)
.toSignalProducer()
.combinePrevious(0)
.filter { (previous, current) -> Bool in
return previous >= 10 && current < 10
}
.on(next: { _ in
// Refilling the queue asynchronously and takes 10 seconds
self.refillQueue(withItemCount: 20)
})
.start()
Another approach would be adding skipRepeats()
after filter
in your original code, but I think combinePrevious
is more explicit in this particular case. 另一种方法是在原始代码中的
filter
之后添加skipRepeats()
,但我认为在这种特殊情况下combinePrevious
更加明确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.