Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable Current and Previous Value

Tags:

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?

like image 483
Stephen H. Gerstacker Avatar asked Mar 17 '16 02:03

Stephen H. Gerstacker


People also ask

How do you find current value of Observable?

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 !==

How do you get the last emitted value from Observable?

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.

What is Observable in IOS Swift?

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.


2 Answers

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)     } } 
like image 82
retendo Avatar answered Nov 15 '22 14:11

retendo


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])> :)

like image 35
Pham Hoan Avatar answered Nov 15 '22 14:11

Pham Hoan