一、debounce语法
public Observable<Integer> getRxJavaDebounceData() {
return Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 1);
emitter.onNext(1);
Thread.sleep(500);
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 2);
emitter.onNext(2);
Thread.sleep(100);
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 3);
emitter.onNext(3);
Thread.sleep(200);
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 4);
emitter.onNext(4);
Thread.sleep(10);
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 5);
emitter.onNext(5);
Thread.sleep(500);
LogUtils.error(TAG, "getRxJavaDebounceData--:" + Thread.currentThread().getName() + "-emitter-:" + 6);
emitter.onNext(6);
}
});
}
public void rxJavaDebounceExample() {
model.getRxJavaDebounceData()
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.debounce(150, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.compose(RxLifeCycleUtils.<Integer>bindUntilEvent(view, ActivityEvent.DESTROY))
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
LogUtils.error(TAG, "rxJavaDebounceExample--:" + Thread.currentThread().getName() + "-consumer-:" + integer);
}
});
}
日志
08-18 16:07:55.628 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:1
08-18 16:07:55.780 29648-29648/com.example.zhang E/MainPresenter: rxJavaDebounceExample--:main-consumer-:1
08-18 16:07:56.130 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:2
08-18 16:07:56.231 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:3
08-18 16:07:56.383 29648-29648/com.example.zhang E/MainPresenter: rxJavaDebounceExample--:main-consumer-:3
08-18 16:07:56.432 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:4
08-18 16:07:56.444 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:5
08-18 16:07:56.597 29648-29648/com.example.zhang E/MainPresenter: rxJavaDebounceExample--:main-consumer-:5
08-18 16:07:56.945 29648-30017/com.example.zhang E/MainModel: getRxJavaDebounceData--:RxCachedThreadScheduler-1-emitter-:6
08-18 16:07:57.097 29648-29648/com.example.zhang E/MainPresenter: rxJavaDebounceExample--:main-consumer-:6
总结
1、debounce去抖动
步骤 : 先发送1,发送器中保存有1
间隔500毫秒发送2,500大于150 ,所以保存1,2
间隔100毫秒发送3 ,100小于150毫秒,用3替换上一个,所以保存1,3
间隔200毫秒发送4,200大于150毫秒,所以保存1,3,4
间隔10毫秒发送5,10小于150毫秒,用5替换4,所以保存1,3,5
间隔500毫秒发送6,500大于150毫秒,所以保存1,3,5,6