在布尔 observable 中只去抖动 false 值 [英] Debounce only false values in boolean observable
问题描述
我有一个布尔值 observable,它(通过观察者)启动和停止 Android 服务.当 true 被传递时,服务必须立即启动.当 false 被传递时,我想对它进行去抖动,以防很快出现 true,以避免不必要的(和破坏性的)停止和启动服务.是否有可以做到这一点的标准运算符的组合,或者我必须自己编写,如果是,我应该基于 OperatorDebounceWithTime.java
还是有更简单的方法?谢谢!
看起来你想要debounce(Func1) 允许您为每个发射的项目定义一个自定义的去抖动窗口.它需要一个函数,为源 Observable 发出的每个项目返回一个 Observable.如果源 Observable 在这个新生成的 Observable 终止之前发出另一个项目,则 debounce 将抑制该项目.
例如,以下代码将立即发出 true
值,并在发出它们之前保持 false
值 2 秒.如果源在计时器到期之前发出另一个 true
值,则 false
将被抑制.
deviceTrigger.distinctUntilChanged().debounce(startDevice -> startDevice?Observable.empty(): Observable.timer(2, TimeUnit.SECONDS)).distinctUntilChanged();
请注意,distinctUntilChanged()
调用可能不是必需的,具体取决于您的源 Observable 是否已经不同并且您的使用者是否连续处理多个 true
值.>
I have a boolean observable that (through a observer) starts and stops an Android service. When true is passed, the service must start immediately. When false is passed, I'd like to debounce it in case a true comes along soon after, to avoid needless (and disruptive) stopping and starting of the service. Is there a composition of standard operators that can do this, or must I write my own, and if so, should I base it on OperatorDebounceWithTime.java
or is there a simpler way? Thanks!
It looks like you want the version of debounce(Func1) that lets you define a custom debounce window for each item emitted. It takes a function that returns an Observable for each item emitted by the source Observable. If the source Observable emits another item before this newly-generated Observable terminates, debounce will suppress the item.
For example, the following code will emit true
values immediately and will hold on to false
values for 2 seconds before emitting them. If the source emits another true
value before the timer expires the false
will be suppressed.
deviceTrigger
.distinctUntilChanged()
.debounce(startDevice -> startDevice
? Observable.empty()
: Observable.timer(2, TimeUnit.SECONDS))
.distinctUntilChanged();
Note that the distinctUntilChanged()
calls may not be necessary depending on if your source Observable is already distinct and your consumer handles multiple true
values in a row.
这篇关于在布尔 observable 中只去抖动 false 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!