RxJava Debounce onNext()

我试图为我的SwitchCompat反弹点击/ swipe没有成功。 下面的代码看起来不错,虽然onNext没有经过debounce()ie:当用户垃圾开关,onNext被称为每次点击,不会因为debounce而被省略。

它应该工作,这与RxJava的错误?

timer = Observable.create { subscriber: Subscriber<in Void>? -> super.setOnCheckedChangeListener { buttonView, isChecked -> subscriber?.onNext(null) } } timer.debounce(3,TimeUnit.SECONDS) 

如果这是你的实际代码,我认为这个问题根本就和debounce无关。 像大多数Rx操作符一样, debounce 返回一个新的Observable – 它不会改变timer指向的那个。

所以,既然你没有在任何地方存储debounce返回的引用,那么基本上什么都不会发生。

尝试: timer = timer.debounce(3, TimeUnit.SECONDS)

你应该使用杰克·沃顿的RxBinding库 。 它将Android小部件封装到Rx中。 对于你有RxCompoundButton,你可以这样使用:

 RxCompoundButton.checkedChanges(switchCompat) .debounce(3, TimeUnit.SECONDS) .subscribe(); 

如果您正在使用Kotlin& RxBinding Kotlin版本 。 你可以在自定义的CompoundButton中表达

 import com.jakewharton.rxbinding.widget.checkedChanges class CustomCompoundButton: CompoundButton { constructor(context: Context): super(context, null) constructor(context: Context, attrs: AttributeSet?): super(context, attrs, 0) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr, 0) fun throttledCheckedChanges() { return this.checkedChanges().debounce(3, TimeUnit.SECONDS) } // OR val throttledCheckedChanges by lazy { this.checkedChanges().debounce(3, TimeUnit.SECONDS) } } // Use it in your activity/ fragment customCompoundButton.throttledCheckedChanges().subscribe { /* do sth */ } // OR customCompoundButton.throttledCheckedChanges.subscribe { /* do sth */ } 

如果你不被允许在你的项目中使用RxBinding 。 你应该看看CompoundButtonCheckedChangeObservable.java来创建一个Rx包装器。