RxJS 获取 Observable 的 before/after 发射值
RxJS get before/after emission values of Observable
我想计算单个 Observable 的发射之间的差异。
如果一个 Observable 发射了一个新值,有没有办法同时获得它的当前发射和上一次发射?
我想要这样的东西:
ob$.subscribe(val => {
console.log(val)
// First emission: [1,2,3]
// Second emission: [1,2,3,4]
console.log(arrayDifference(before, after)) // [4]
})
我该怎么做?我是否需要将每个发射存储在一个上层变量中,或者是否有一种奇特的 RxJS 方式来做到这一点?
您可以使用非常模块化的 bufferCount
运算符来做到这一点:
bufferCount(2, 1)
它会在每次 1
从源发射后创建一个大小为 2
的新缓冲区。
或者,还有 pairwise()
运算符做完全相同的事情。
我会使用 startWith 和 pairwise()
const randomObservable = of('observableString')
.pipe(startWith('defaultString'), pairwise())
.subscribe(arrayOfStrings => console.log(arrayOfStrings[0], arrayOfStrings[1]));
上面的代码将控制台日志:'defaultString'、'observableString'。
使用扫描运算符检查之前的值
const arrayDifference = (before, after) => {
// Immlement the fuction here
const difference = .........
return difference
}
ob$.pipe(scan((before,after) => arrayDifference(before,after), [])).subscribe(val => console.log(val))
这应该有效
我想计算单个 Observable 的发射之间的差异。
如果一个 Observable 发射了一个新值,有没有办法同时获得它的当前发射和上一次发射? 我想要这样的东西:
ob$.subscribe(val => {
console.log(val)
// First emission: [1,2,3]
// Second emission: [1,2,3,4]
console.log(arrayDifference(before, after)) // [4]
})
我该怎么做?我是否需要将每个发射存储在一个上层变量中,或者是否有一种奇特的 RxJS 方式来做到这一点?
您可以使用非常模块化的 bufferCount
运算符来做到这一点:
bufferCount(2, 1)
它会在每次 1
从源发射后创建一个大小为 2
的新缓冲区。
或者,还有 pairwise()
运算符做完全相同的事情。
我会使用 startWith 和 pairwise()
const randomObservable = of('observableString')
.pipe(startWith('defaultString'), pairwise())
.subscribe(arrayOfStrings => console.log(arrayOfStrings[0], arrayOfStrings[1]));
上面的代码将控制台日志:'defaultString'、'observableString'。
使用扫描运算符检查之前的值
const arrayDifference = (before, after) => {
// Immlement the fuction here
const difference = .........
return difference
}
ob$.pipe(scan((before,after) => arrayDifference(before,after), [])).subscribe(val => console.log(val))
这应该有效