Reputation: 423
let's say you are observing a property that changes quite often, e.g. 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. 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
Upvotes: 0
Views: 42
Reputation: 7944
I think you can use combinePrevios
operator here, as it gives you the present and the previous value:
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.
Upvotes: 0