无初始延迟去抖 [英] Debounce without initial delay
问题描述
RxJS 中是否有一个操作符可以在不延迟突发中的第一个事件"的情况下进行去抖动,但会延迟(并始终发出)突发中的最后一个事件"?
Is there an operator in RxJS that debounces without delaying the "first event in a burst", but delaying (and always emitting) the "last event in a burst"?
像这样:
---a----b-c-d-----e-f---
在 awesome-debounce(2 dashes)
之后变成:
---a----b------d--e----f
而正常的去抖动是:
-----a---------d-------f
这是油门和去抖动的混合......
It's kind of a mix between throttle and debounce...
推荐答案
嗯,这是我能想到的最简单的解决方案.对您来说有趣的部分是创建子链的 awesomeDebounce()
函数.
Hmmm, this is the easiest solution I can think of. The interesting part for you is the awesomeDebounce()
function that creates the sub-chain.
它基本上只是结合了 throttle()
和 debounceTime()
操作符:
It basically just combines throttle()
and debounceTime()
operators:
const Rx = require('rxjs');
const chai = require('chai');
let scheduler = new Rx.TestScheduler((actual, expected) => {
chai.assert.deepEqual(actual, expected);
console.log(actual);
});
function awesomeDebounce(source, timeWindow = 1000, scheduler = Rx.Scheduler.async) {
let shared = source.share();
let notification = shared
.switchMap(val => Rx.Observable.of(val).delay(timeWindow, scheduler))
.publish();
notification.connect();
return shared
.throttle(() => notification)
.merge(shared.debounceTime(timeWindow, scheduler))
.distinctUntilChanged();
}
let sourceMarbles = '---a----b-c-d-----e-f---';
let expectedMarbles = '---a----b------d--e----f';
// Create the test Observable
let observable = scheduler
.createHotObservable(sourceMarbles)
.let(source => awesomeDebounce(source, 30, scheduler));
scheduler.expectObservable(observable).toBe(expectedMarbles);
scheduler.flush();
内部 notification
Observable 仅用于 throttle()
运算符,因此我可以在需要时手动重置其计时器.我还必须将这个 Observable 变成 "hot" 以独立于来自 throttle()
的内部订阅.
The inner notification
Observable is used only for the throttle()
operator so I can reset its timer manually when I need. I also had to turn this Observable into "hot" to be independent on the internal subscriptions from throttle()
.
这篇关于无初始延迟去抖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!