0

假设您正在观察一个经常变化的属性,例如,当它低于阈值时应该重新填充的队列?

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()

当队列为空时,将触发下一个处理程序并填充队列。在填充队列时,SignalProducer 发送一个新的下一个事件,因为 count 属性更改为 1 - 一个又一个。但我不希望触发下一个处理程序。相反,我希望每次队列低于该阈值时触发一次。

我怎样才能以最好的方式做到这一点?是否有任何有用的事件流操作?有任何想法吗?

干杯,

杰拉尔多

4

1 回答 1

0

我认为您可以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()

另一种方法是在原始代码中添加skipRepeats()之后filter,但我认为combinePrevious在这种特殊情况下更为明确。

于 2016-02-14T16:29:34.077 回答