根据另一个 Observable 的输出去抖一个 Observable

Debounce an Observable based on the output of another observable

我正在寻找合适的运算符和一种优雅的方法来根据另一个的输出时间对一个可观察对象进行去抖动。

基本问题:

'If during the past 3 seconds observable A has emitted, debounce the emit of Observable B until these three seconds have passed'

此外,这在 NGRX actions/effects 的上下文中应用,在此上下文中改写基本问题会产生:

'Debounce an effect based on the recent history of another effect or action'

这应该可以满足您的需求:

const since = Date.now();

const actionA = new Rx.Subject();
const actionB = new Rx.Subject();

const debouncedB = Rx.Observable
  .combineLatest(
    actionA.switchMap(() => Rx.Observable.concat(
      Rx.Observable.of(true),
      Rx.Observable.of(false).delay(3000)
    ))
    .startWith(false),
    actionB
  )
  .filter(([debouncing]) => !debouncing)
  .map(([, b]) => b)
  .distinctUntilChanged();

debouncedB.subscribe(
  (value) => console.log(value, `T+${((Date.now() - since) / 1000).toFixed(0)}`)
);

actionB.next("b1");
actionA.next("a1");
actionB.next("b2");
actionB.next("b3");
actionB.next("b4");

setTimeout(() => actionB.next("b5"), 4000);
setTimeout(() => actionA.next("a2"), 5000);
setTimeout(() => actionB.next("b6"), 6000);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

它将每个 A 动作转换为 truefalse 的去抖动信号。当true时,B动作会去抖,直到信号变成false.

switchMap 用于如果在信号为 true 时收到另一个 A 动作,信号将不会设置为 false,直到最近的 A 动作后三秒.