Debounce without initial delay

丶灬走出姿态 提交于 2019-12-05 06:39:37
martin

Hmmm, this is the easiest solution I can think of. The interesting part for you is the awesomeDebounce() function that creates the sub-chain.

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();

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().

Vladimir Tolstikov

That's indeed useful debounce type for many situations. Use merge, throttleTime and debounceTime in a next way:

Rx.Observable.merge(source.throttleTime(1000), source.debounceTime(2000))

Full example is here http://jsbin.com/godocuqiwo/edit?js,console

Note: it will emit not only first and last value in debounce interval but also values produced by throttle (which is usually expected and needed, as for scroll debouncing for example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!