关于RXbinding的一些常规使用

时间:2021-07-21 10:50:14

先说导包

 /*rx的引入*/
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.9'
//RXbinding https://github.com/JakeWharton/RxBinding
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'


1,防止多次点击

 //1.对于button的防抖处理 2秒内只截取第一次的点击事件,还有一个截取最后一次的方法
//throttleFirst(2, TimeUnit.SECONDS) 截取第一个事件
//throttleWithTimeout(2,TimeUnit.SECONDS) 事件延迟两秒执行
RxView.clicks(button).throttleLast(2, TimeUnit.SECONDS)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {

}

@Override
public void onNext(@NonNull Object o) {
Log.e("收到点击事件","==="+System.currentTimeMillis());
}

@Override
public void onError(@NonNull Throwable e) {

}

@Override
public void onComplete() {

}
});
2.多少秒后再次发送验证码

//2.按钮实现倒计时,屏蔽点击事件+定时
RxView.clicks(button)
.subscribeOn(AndroidSchedulers.mainThread())
.throttleFirst(60, TimeUnit.SECONDS)//60S后可以再次发送
.subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {

}

@Override
public void onNext(@NonNull Object o) {
Log.e("点击事件", "点击事件");
Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.take(60)
.subscribe(new Observer<Long>() {

@Override
public void onSubscribe(@NonNull Disposable d) {

}

@Override
public void onNext(@NonNull Long aLong) {
button.setText(60 - aLong + "S后可发送");
}

@Override
public void onError(@NonNull Throwable e) {

}

@Override
public void onComplete() {
button.setText("发送验证码");

}
});
}

@Override
public void onError(@NonNull Throwable e) {

}

@Override
public void onComplete() {

}
});