简体   繁体   中英

ReactiveCocoa - SignalProducer that emits the latest N values in array

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?

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
        }
    }
}
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]

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