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?
To get current value of RxJS Subject or Observable, we can use the first method. const observable = of("foo"); const hasValue = (value: any) => { return value !==
Rather than a standard subject (Observable) that just emits values as they come in, a BehaviorSubject emits the last value upon subscribe() . You can also get the last value manually using the BehaviorSubjects getValue() method.
Observable-Swift is a Swift library for value observing (via explicit usage of Observable<T> ) and subscribable events (also explicit, using Event<T> ). While it is not exactly "KVO for Swift" (it is explicit, there are no "Keys", ...) it is a catchy name so you can call it that if you want.
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) } }
there you go
options.asObservable() .scan( [ [],[] ] ) { seed, newValue in return [ seed[1], newValue ] } // optional, working with tuple of array is better than array of array .map { array in (array[0], array[1]) } //optional, in case you dont want empty array .skipWhile { $0.count == 0 && $1.count == 0 }
it will return Observable<([Options], [Options])>
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With