我可以观察到每N秒发射一次值。我想获取第一个发射,并在此发射函数。
我有这个代码:
sideEffect = false;
observable$
.pipe(
tap((data) => {
// executing this only for the first emission
if (!sideEffect) {
this.sideEffect(data.props);
sideEffect = true;
}
})
)
.subscribe((data) => {
// process all upcoming emissions
});
有没有办法在不定义任何局部变量的情况下使用RxJS运算符使代码变得更好?
我将继续创建两个独立的Observable,然后合并它们,这样我们就可以有一个单独的订阅。我认为这是通过rxjs实现此逻辑的最常用方法。
代码看起来像这个
const firstEmission$ = observable$
.pipe(
take(1), // you can use also the first() operator which is the same as take(1)
tap((data) => this.sideEffect(data.props))
);
const otherEmissions$ = observable$
.pipe(
skip(1),
);
merge(firstEmission$, otherEmissions$).subscribe((data) => {
// process all upcoming emissions
});
有一个scan
运算符可以解决您的问题:
const stream$ = from([1,2,3,4]).pipe(
scan((firstValue, value) => {
if (!firstValue) {
firstValue = value;
console.log('performing side effects for value: ', value);
}
return value;
}, null),
map(value => { /* your further logic here */ return value; })
);
CCD_ 2为每次发射调用,并将值存储在其内部。它类似于数组中的reduce
函数。还要注意;falsy";值可能表现不正确(由于!firstValue
检查(