简体   繁体   中英

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. 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM