RxJava 去抖 onNext()

RxJava Debounce onNext()

我正在尝试为我的 SwitchCompat 去抖 clicks/swipes 但没有成功。 下面的代码看起来不错,尽管 onNext 没有通过 debounce() 即:当用户向开关发送垃圾邮件时,每次点击都会调用 onNext,而不是由于去抖动而被省略。

它应该可以工作,这是 RxJava 的错误吗?

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

如果这是您的实际代码,我认为问题根本与 debounce 无关。像大多数 Rx 运算符一样,debounce returns 一个新的 Observable - 它不会改变 timer 指向的对象。

因此,由于您没有将 debounce 返回的引用存储在任何地方,基本上什么都不会发生。

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

您应该使用 Jake Wharton 的 RxBinding library。它将 android 小部件包装到 Rx 中。为您提供 RxCompoundButton,您可以像这样使用它:

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

如果您使用的是 Kotlin & RxBinding Kotlin Version。您可以在自定义的 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 in your project. You should take a look CompoundButtonCheckedChangeObservable.java 创建 Rx 包装器。