Debounce only false values in boolean observable

冷暖自知 提交于 2020-01-03 21:50:27

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/32962445/debounce-only-false-values-in-boolean-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!