2

I have a SignalProducer, ProducerA, that emits values in various intervals. I am trying to collect the latest N values that the SignalProducer emits and create a new producer, ProducerB, that emits an array containing the latest N values.

ProducerB should start emitting values when ProducerA emits the first N values, and then emit a new array each time ProducerA emits a new value.

Can someone help me?

gkaimakas
  • 574
  • 3
  • 17

2 Answers2

1

I came up with this code

extension SignalProducer {
    /// Creates a new producer that emits an array that contains the latest N values that were emitted 
    /// by the original producer as specified in 'capacity'.
    @warn_unused_result(message="Did you forget to call `start` on the producer?")
    public func latestValues(n:Int) -> SignalProducer<[Value], Error> {
        var array: [Value] = []
        return self.map {
            value in

            array.append(value)

            if array.count >= n {
                array.removeFirst(array.count - n)
            }

            return array
        }
            .filter {
                $0.count == n
        }
    }
}
gkaimakas
  • 574
  • 3
  • 17
1
let (producerA, observerA) = SignalProducer<Int, NoError>.buffer(5)
let n = 3

producerA.take(n).collect()
        .takeUntilReplacement(producerA.skip(n).map { [$0] })
        .scan([], { $0.suffix(n - 1) + $1 })
        .startWithNext {
                print($0)
}

observerA.sendNext(1) // nothing printed
observerA.sendNext(2) // nothing printed
observerA.sendNext(3) // prints [1, 2, 3]
observerA.sendNext(4) // prints [2, 3, 4]
observerA.sendNext(5) // prints [3, 4, 5]
linimin
  • 6,239
  • 2
  • 26
  • 31
  • that is not the desired result. In your code, you specify n=3 meaning that the array should be of size 3. Accepted result would be for n=3: observerA.sendNext(1) // nothing printed observerA.sendNext(2) // nothing printed observerA.sendNext(3) // prints [1, 2, 3] observerA.sendNext(4) // prints [2, 3, 4] observerA.sendNext(5) // prints [3, 4, 5] – gkaimakas Feb 05 '16 at 10:58