34
votes

I have a BehaviorSubject which emits JavaScript objects periodically. I want to construct another observable which will emit both previous and current values of the underlying observable in order to compare two objects and determine the delta.

The pairwise() or bufferCount(2, 1) operators are looking like a good fit, but they start emitting only after buffer is filled, but I require this observable to start emitting from the first event of the underlying observable.

subject.someBufferingOperator()
    .subscribe([previousValue, currentValue] => {
        /** Do something */
    })
;

On first emission the previousValue could be just null.

Is there some built-in operators that I can use to achieve the desired result?

2

2 Answers

81
votes

Actually, it was as easy as pairing pairwise() with startWith() operators:

subject
    .startWith(null) // emitting first empty value to fill-in the buffer
    .pairwise()
    .subscribe([previousValue, currentValue] => {
        if (null === previousValue) {
            console.log('Probably first emission...');
        }
    })
;
0
votes

Here's the snippet for rxjs 6+

subject
    .pipe(
       startWith(undefined),
       pairwise()
    )
    .subscribe(([previousValue, currentValue]) => {
        /** Do something */
    });

The value in startWith() should be undefined because there is no value. Typically null is defined as "we have a value and this value is empty".