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