根据另一个的过去值过滤一个Observable

时间:2018-08-01 01:06:16

标签: javascript rxjs reactive-programming

因此,我有两个可观察的click$focus$。我希望只有在过去500毫秒内没有任何焦点事件时,点击才能通过

我尝试过skipWhile。但是我迷失了要弄清楚里面要放什么的东西。

click$.skipWhile(/* No focus$ events in the past 500ms*/).subscribe()

请指向正确的方向。

1 个答案:

答案 0 :(得分:1)

通过基于焦点事件组成一个可观察对象,您应该能够做您想要的事情。像这样:

const focusedClick$ = focus$
  // Switch to the click observable, but only after the specified
  // duration has elapsed:
  .switchMap(() => Observable.timer(500).ignoreElements().concat(click$));

如果可以通过单击事件而没有前面的焦点事件,则可以使用startWith运算符解决该问题:

const focusedClick$ = focus$
  // Map the focus event to a duration:
  .mapTo(500)
  // Start the observable chain with a duration of zero, so click
  // events don't have to be preceded by focus events:
  .startWith(0)
  // Switch to the click observable, but only after the specified
  // duration has elapsed:
  .switchMap(duration => Observable.timer(duration).ignoreElements().concat(click$));