swiftreactive-cocoacombinereactive-swift

Combine previous value using Combine


How can I rewrite ReactiveSwift/ReactiveCocoa code using Combine framework? I attached screenshot what combinePrevious mean from docs.

let producer = SignalProducer<Int, Never>([1, 2, 3]).combinePrevious(0)
producer.startWithValues { value in
    print(value) // print: (0, 1), (1, 2), (2, 3)
}

enter image description here


Solution

  • I'm not completely familiar with ReactiveSwift/ReactiveCocoa, but based on your description, you can use .scan, which seems to be a more general function than combinePrevious.

    It takes an initial result - which you can make into a tuple -, and a closure with the stored value and the current value, and returns a new stored value - in your case, a tuple with (previous, current):

    let producer = [1,2,3].publisher
                          .scan((0,0)) { ($0.1, $1) }
    
    producer.sink { 
       print($0) 
    }