Observable Current and Previous Value

Stephen H. Gerstacker picture Stephen H. Gerstacker · Mar 17, 2016 · Viewed 17.1k times · Source

I have a Variable which is an array of enum values. These values change over time.

enum Option {
    case One
    case Two
    case Three
}

let options = Variable<[Option]>([ .One, .Two, .Three ])

I then observe this variable for changes. The problem is, I need to know the diff between the newest value and the previous value. I'm currently doing this:

let previousOptions: [Option] = [ .One, .Two, .Three ]

...

options
    .asObservable()
    .subscribeNext { [unowned self] opts in
        // Do some work diff'ing previousOptions and opt
        // ....
        self.previousOptions = opts
    }

Is there something built in to RxSwift that would manage this better? Is there a way to always get the previous and current values from a signal?

Answer

retendo picture retendo · May 29, 2017

Here is a handy generic extension, that should cover these "I want the previous and the current value" use cases:

extension ObservableType {

    func withPrevious(startWith first: E) -> Observable<(E, E)> {
        return scan((first, first)) { ($0.1, $1) }.skip(1)
    }
}