debounce(过滤操作符)
目录
debounce很有意思的一个词,去抖,要明白debounce的用法首先要知道什么是“去抖”
1 debounce:去抖
当调用函数N秒后,才会执行函数中动作,若在这N
秒内又重复调用该函数则将取消前一次调用,并重新计算执行时间。
这个debounce在js常被使用,比如界面根据用户输入做ajax请求局部刷新页面,那么势必会重复请求接口,而实际可能在n秒内用户并没有完成输入,那么频繁调函数肯定是不准确的,那么可以设定一个debounce time,在n秒内的调用都是无效的。
2 throttle 节流
与之相对的是throttle,节流,网络上有个很形象的比喻:如果将水龙头拧紧直到水是以水滴的形式流出,那你会发现每隔一段时间,就会有一滴水流出。
也就是会说预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期。throttle会在后面分析。
3 debounce接口
<U> Flowable<T> | debounce(Function<? super T,? extends Publisher<U>> debounceIndicator) Returns a Flowable that mirrors the source Publisher, except that it drops items emitted by the source Publisher that are followed by another item within a computed debounce duration. 返回一个镜像源Publisher的Flowable,它会丢弃源Publisher在去抖时间内紧跟着发出的项目(也就是在n秒内会发送多个项目,因为在去抖时间内,将会丢弃) |
Flowable<T> | debounce(long timeout, TimeUnit unit) Returns a Flowable that mirrors the source Publisher, except that it drops items emitted by the source Publisher that are followed by newer items before a timeout value expires. 返回镜像源Publisher的Flowable,但它会丢弃源Publisher发出的项,这些项后面跟着在超时值到期之前新发射的项(简单点说就是,比如超时时间是1s,在1s内Publisher会发射多个值,在这个时间内,最后发射的项才会有效,它前面发射的项目都要被丢弃) |
Flowable<T> | debounce(long timeout, TimeUnit unit, Scheduler scheduler) Returns a Flowable that mirrors the source Publisher, except that it drops items emitted by the source Publisher that are followed by newer items before a timeout value expires on a specified Scheduler. 返回一个镜像源Publisher的Flowable,它在指定的Scheduler上超时值到期之前删除源Publisher发出的后跟更新项的项。 (翻译有些绕口,只要明白什么是debounce这些就不难理解了 |
4 debounce图解说明
如果特定的时间跨度已经过去而没有发出另一个项目,则只从Observable中发出一个项目
5 ebounce测试用例
@Test
public void debounce() {
System.out.println("######debounce#####");
Flowable flowable = Flowable.just("李晓明", "张宝庆","赵无极")
.debounce(1,TimeUnit.MILLISECONDS);
flowable.subscribe(new Consumer<String>() {
@Override
public void accept(String value) throws Exception {
System.out.println("value = " + value);
}
});
}
测试结构
######debounce#####
value = 赵无极
6 debounce测试用例说明
上面测试用例为了达到效果特别设置了去抖时间是1ms,也就是说“赵无极”发射时间因为在去抖时间之内,所以其前面发射的项被丢弃掉了,之中只是计算了它(赵无极)。这个操作符需要结合场景来理解,比如说,1秒内有新数据,那么久丢弃旧数据。
其他操作符