RxJS observable which emits both previous and current value starting from first emission

故事扮演 提交于 2020-05-25 06:06:33

问题


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?


回答1:


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...');
        }
    })
;


来源:https://stackoverflow.com/questions/50059622/rxjs-observable-which-emits-both-previous-and-current-value-starting-from-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!