我正在使用 Reactive Extensions ' combine_latest
每当任何输入打勾时执行一个 Action 。问题是,如果多个 输入在同时 跳动,则combine_latest
在每个单独的输入跳动后触发多次。这会让人头疼,因为 combine_latest
实际上是在用陈旧的值进行虚假滴答。
最小工作示例,其中 fast
observable 每 10ms 滴答一次,slow
observable 每 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)
每 30 毫秒,当 fast
和 slow
同时跳动时,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}
我怎样才能防止 combine_latest
虚假地滴答作响?
最佳答案
我认为 debounce
完全符合您的要求:
---A-B-C-----D------E-F----|->
[debounce(some_interval)]
--------C-----D--------F---|->
得到一个值A
后,debounce
会等待some_interval
。如果出现另一个值 B
,它将发出 B
。因此,您可以对输入流进行去抖动处理,这将“捕获”那些额外的点击并仅发出最后一次点击。
(很久以前就有人问过这个问题,但我正在为 future 的 google 员工回答。)
关于python - 当多个输入同时滴答时,如何防止 combine_latest 多次触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567764/