如何使用 RxJS 控制按钮行为?

How to control button behaviors with RxJS?

假设我有一个按钮和一个流,它是多个流的组合,如下所示:

let button = Rx.Observable.fromEvent($('#button'), 'click')
let source = Rx.Observable.combineLatest(multiple_source, (...val) => val)

我想要以下操作:

我试过以下但没有成功:

// `source` keep yielding values after button is clicked
button.flatMap( () => source).subscribe(val => do sth...) 

// `source` only yield values once but not yielding values 
// when some input changes
button.flatMap( () => source.take(1)).subscribe(val => do sth...) 

// `source` only yield values when button is clicked. 
// But like the above case, it stop yielding values 
// when some input changes
source.takeUntil(button).subscribe(val => do sth...) 

我发现在这种情况下工作的是 Observable#withLatestFrom。我不确定这是否是最好的方法,如果有更简单的方法更好,那就太好了。这是我经常使用的工具。

在您的示例中,您可以执行以下操作:

button.withLatestFrom(source, (_, src) => src).subscribe(doSomething)

我只是删除了按钮事件,因为您在示例中似乎并不关心它。

这里有一个快速的 fiddle 只是为了更好的衡量。希望这与您正在寻找的内容相似:https://jsfiddle.net/pkoq9n6b/