RxJS可观察到,从第一次发射开始既发射先前值,又发射当前值 [英] RxJS observable which emits both previous and current value starting from first emission

查看:112
本文介绍了RxJS可观察到,从第一次发射开始既发射先前值,又发射当前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 BehaviorSubject ,它会定期发出JavaScript对象.我想构造另一个可观察对象,该对象将发出基础可观察对象的先前值和当前值,以便比较两个对象并确定增量.

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.

pairwise() bufferCount(2, 1) 运算符正在寻找就像一个很好的拟合,但是它们仅在缓冲区填充后才开始发出,但是我要求此可观察对象从基础可观察对象的第一个事件开始发出.

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 */
    })
;

第一次发射时,previousValue可能只是null.

是否可以使用一些内置运算符来获得所需的结果?

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

推荐答案

实际上,这和配对

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

这篇关于RxJS可观察到,从第一次发射开始既发射先前值,又发射当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆