【问题标题】:ReactiveCocoa - SignalProducer that emits the latest N values in arrayReactiveCocoa - 发出数组中最新 N 值的 SignalProducer
【发布时间】:2016-04-12 09:32:52
【问题描述】:

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

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

有人可以帮我吗?

【问题讨论】:

    标签: ios swift reactive-cocoa-3


    【解决方案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]
    

    【讨论】:

    • 这不是我们想要的结果。在您的代码中,您指定 n=3 表示数组的大小应为 3。接受的结果将是 n=3:observerA.sendNext(1) // 没有打印 observerA.sendNext(2) // 没有打印observerA。 sendNext(3) // 打印 [1, 2, 3] observerA.sendNext(4) // 打印 [2, 3, 4] observerA.sendNext(5) // 打印 [3, 4, 5]
    【解决方案2】:

    我想出了这个代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多