【发布时间】:2021-04-14 08:51:41
【问题描述】:
我正在尝试使用 RxJS debounce 运算符,但我想自定义源的排放何时被去抖。
默认情况下,来自去抖窗口内的源的任何发射都会导致之前的发射被丢弃。我希望根据源排放的值,只有某些源排放计入去抖操作。
假设我有一个如下所示的可观察对象:
{
priority: 'low' //can be 'low' or 'medium' or 'high
}
我希望去抖动按对象的优先级分组。这意味着只有当一个发射具有相同的优先级时,它才会被另一个发射去抖动。
即只有'low' 排放可以去抖动'low' 排放,并且只有'high' 排放可以去抖动'high' 排放。如果'medium' 发射在'low' 发射等待时出现,则不会导致'low' 发射被丢弃。
这意味着如果我有一个'low' 发射和一个'medium' 发射快速连续,两者都会通过。如果我快速连续发出两个'low',则只有最后一个会通过。
这是我想出的:
const $source = // some observable of type { priority: 'low' | 'medium' | 'high' }
const delay = 1000
$source.pipe(
mergeMap(value => {
// We start a race of the value with a delay versus any other emissions from the source with the same priority
return race(
timer(delay).pipe(mapTo(value)),
$source.pipe(
filter(v => v.priority === value.priority),
)
).pipe(
take(1),
// If another emission with the same priority comes before the delay, the second racer it will win the race.
// If no emission with the same priority comes, the first racer will win.
//
// If the first racer wins, this equality check is satisfied and the value is passed through.
// If the second racer wins, the equality check fails and no value is emitted. Since this is a mergeMap, this whole process will start again for that emission.
filter(v => v === value),
)
})
)
我认为以上是正确的,但我想知道我是否遗漏了某些东西或使这种方式比需要的更复杂?上面的代码应该像合并$low.pipe(debounceTime(delay)) $medium.pipe(debounceTime(delay)) 和$high.pipe(debounceTime(delay)) 的三个独立流一样运行。
谢谢!!
【问题讨论】:
标签: javascript rxjs reactive-programming redux-observable