当多个输入同时打勾时,如何防止 combine_latest 多次触发?

mch*_*hen 5 python reactive-programming rx-py

我正在使用Reactive Extensions 'combine_latest在任何输入勾选时执行操作。问题是如果多个输入蜱在同一时间然后combine_latest触发各个输入蜱后多次。这会引起头痛,因为combine_latest它实际上是用陈旧的值进行虚假滴答。

最小工作示例,其中fastobservable 每 10ms 滴答一次,而slowobservable 每 30ms 滴答一次:

from rx.concurrency import HistoricalScheduler
from rx import Observable
from __future__ import print_function

scheduler = HistoricalScheduler(initial_clock=1000)
fast = Observable.generate_with_relative_time(1, lambda x: True, lambda x: x + 1, lambda x: x, lambda x: 10, scheduler=scheduler)
slow = Observable.generate_with_relative_time(3, lambda x: True, lambda x: x + 3, lambda x: x, lambda x: 30, scheduler=scheduler)
Observable.combine_latest(fast, slow, lambda x, y: dict(time=scheduler.now(), fast=x, slow=y)).subscribe(print)
scheduler.advance_to(1100)
Run Code Online (Sandbox Code Playgroud)

每 30 毫秒,当fastslow滴答同时发生时,combine_latest不希望地触发两次——输出如下:

{'slow': 3, 'fast': 2, 'time': 1030}  # <- This shouldn't be here
{'slow': 3, 'fast': 3, 'time': 1030}
{'slow': 3, 'fast': 4, 'time': 1040}
{'slow': 3, 'fast': 5, 'time': 1050}
{'slow': 6, 'fast': 5, 'time': 1060}  # <- This shouldn't be here
{'slow': 6, 'fast': 6, 'time': 1060}
{'slow': 6, 'fast': 7, 'time': 1070}
{'slow': 6, 'fast': 8, 'time': 1080}
{'slow': 9, 'fast': 8, 'time': 1090}  # <- This shouldn't be here
{'slow': 9, 'fast': 9, 'time': 1090}
{'slow': 9, 'fast': 10, 'time': 1100}
Run Code Online (Sandbox Code Playgroud)

如何防止combine_latest虚假滴答声?

ury*_*yga 2

我认为debounce这正是你想要的:

---A-B-C-----D------E-F----|->
  [debounce(some_interval)]
--------C-----D--------F---|->
Run Code Online (Sandbox Code Playgroud)

得到一个值后Adebounce就会等待some_interval。如果B出现另一个值,它将发出B。因此,您可以对输入流进行去抖动处理,这将“捕获”这些额外的点击并仅发出最后一次点击。

更多内容请参见官方文档

(这个问题很久以前就被问到了,但我是为未来的谷歌用户回答的。)