ReactiveCocoa - 在阵列中发出最新N值的SignalProducer

时间:2016-01-07 20:28:46

标签: ios swift reactive-cocoa-3

我有一个SignalProducer,ProducerA,它以不同的间隔发出值。我正在尝试收集SignalProducer发出的最新N值,并创建一个新的生产者ProducerB,它发出一个包含最新N值的数组。

当ProducerA发出前N个值时,ProducerB应该开始发光值,然后每次ProducerA发出一个新值时都会发出一个新数组。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我想出了这段代码

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

答案 1 :(得分:0)

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]