RxJS observable,它从第一次发射开始发射前一个值和当前值 [英] RxJS observable which emits both previous and current value starting from first emission

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

问题描述

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

pairwise()bufferCount(2, 1) 操作符看起来很合适,但它们只有在缓冲区被填充后才开始发射,但我需要这个 observable 从底层 observable 的第一个事件开始发射.

subject.someBufferingOperator().subscribe([previousValue, currentValue] => {/** 做一点事 */});

<块引用>

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

是否有一些内置的运算符可以用来实现预期的结果?

解决方案

实际上,就像配对 pairwise()startWith() 操作符:

主题.startWith(null)//发出第一个空值来填充缓冲区.pairwise().subscribe([previousValue, currentValue] => {if (null === previousValue) {console.log('可能是第一次发射...');}});

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?

解决方案

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 observable,它从第一次发射开始发射前一个值和当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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