RxJava2 Flowable debounce(过滤操作符)去重复操作

本文详细介绍了RxJava2中Flowable的debounce操作符,主要用于去抖动,即在特定时间间隔内,只有最后一次操作会被执行。内容包括debounce的原理、用法、图解说明及测试用例,旨在帮助理解如何在实际场景中如用户输入时避免频繁请求,提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

debounce(过滤操作符)

目录

1 debounce:去抖

2 throttle 节流

4 debounce图解说明

5 ebounce测试用例

6 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秒内有新数据,那么久丢弃旧数据。

 

其他操作符

delay delaySubscription(辅助操作符)

delaySubscription(辅助操作符)

switchIfEmpty(条件操作符)

debounce(过滤操作符)去重复操作

count(统计操作符)

contains(条件操作符)

concatWith(连接操作符)

concatMap(变换操作符)

collect & collectInto

cast

cache

buffer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值