java实现debounce_Rxjava debounce 操作符

Debounce

1.官方定义

only emit an item from an Observable if a particular timespan has passed without it emitting another item

java实现debounce_Rxjava debounce 操作符_第1张图片

The Debounce operator filters out items emitted by the source Observable that are rapidly followed by another emitted item.

2.API

public final Observable debounce(long timeout, TimeUnit unit); //默认执行线程 Schedulers.computation()

public final Observable debounce(long timeout, TimeUnit unit, Scheduler scheduler);

3.Android中使用场景

快速点击按钮,执行某个操作。

java实现debounce_Rxjava debounce 操作符_第2张图片

java实现debounce_Rxjava debounce 操作符_第3张图片

比如美团APP中的选择套餐:由左图的0份快速点击到右图的7份,然后根据选中份数计算总价。

4.代码实现一

//NumberPickerView.java

...

plusView.setOnClickListener(v- >{

selectCount++;

countTv.setText(selectCount+ "");

onChangeListener.onChange(dealId, selectCount);//dealId为当前套餐的id

});public interfaceOnChangeListener {

onChange(int dealId, intselectCount);

}

//activity

...

numberPickerView.setOnChangeListener((dealId, selcetCount)->{

calculateDealPrice(dealId, selectCount);

});private calculateDealPrice(int dealId, intselectCount) {

...//计算价格

}

对于这种快速点击,我们其实需要的是对第7次进行计算,中间的一系列暂存态是没必要计算的,使用debounce来解决。

5.代码实现二:增加debounce操作

RxView.clicks(plusView)

.map(aVoid->{

selectCount++;

countTv.setText(selectCount+ "");returnselectCount;

}

.debounce(400, TimeUnit.MILLISECONDS))

.observeOn(AndroidSchedulers.mainThread())

.subcribe(count-> onChangeListener.onChange(dealId, selectCount), Throwable::printStackTrace);

缺点:

1.NumberPickerView依赖了 com.jakewharton.rxbinding:rxbinding:x.x.x

2.NumberPickerView中plusView被强制增加了400ms的debounce操作

5.代码实现三:将debounce操作移出NumberPickerView

//NumberPickerView.java

...

plusView.setOnClickListener(v- >{

selectCount++;

countTv.setText(selectCount+ "");

onChangeListener.onChange(dealId, selectCount);//dealId为当前套餐的id

});

//activity

...

PublishSubject subject =PublishSubject.create();

numberPickerView.setOnChangeListener((dealId, selectCount)->{

subject.onNext(newSelectParams(dealId, selectCount));

});

subject.debounce(400, TimeUnit.MILLISECONDS)

.observeOn(AndroidSchedulers.mainThread())

.subscribe(selectParams->calculateDealPrice(selectParams.dealId, selectParams.selectCount), Throwable::printStackTrace);classSelectParams {intdealId;intselectCount;

SelectParams(int dealId, intselectCont) {this.dealId =dealId;this.selectCount =selectCount;

}

}private calculateDealPrice(int dealId, intselectCount) {

...//计算价格

}

此时NumberPickerView不再依赖第三方库,适用性提高。

参考:http://reactivex.io/documentation/operators.html

原文:http://www.cnblogs.com/ruyingxiangsui/p/6082777.html

你可能感兴趣的:(java实现debounce)