本文主要是介绍rxjava : 过滤操作符 : throttleFirst、sample/throwttleLast、throttleWithTimeout/debounce,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考:
RxJava 1.x 笔记:过滤型操作符
RxJava----操作符:过滤操作符
目录:
throttleWithTimeout 和 debounce
throttleLast 和 sample
throttleWithTimeout 和 debounce
每产生一个数据后,如果在规定的间隔时间内没有别的数据产生,就会发射这个数据,否则忽略该数据。
throttleWithTimeout 和 debounce 作用一样,通过源码可以看到,它也是调用的 debounce:
//调用debounce()
public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) {return debounce(timeout, unit);
}public final Observable<T> debounce(long timeout, TimeUnit unit) {return debounce(timeout, unit, Schedulers.computation());
}
throttleLast 和 sample
在一个指定的时间间隔里由Observable发射最近一次(最后一次)的数值。
如果我们想让它定时发射第一个元素而不是最近的一个元素,我们可以使用throttleFirst()。
throttleLast 和 sample 一样,只不过名称不同:
//调用sample()
public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) {return sample(intervalDuration, unit);
}public final Observable<T> sample(long period, TimeUnit unit) {return sample(period, unit, Schedulers.computation());
}
示例:
Sample操作符会定时地发射【源Observable最近发射的数据】,其他的都会被过滤掉,等效于ThrottleLast操作符。
public void sample(String tag) {Disposable disposable = Observable.intervalRange(0, 100, 0, 1, TimeUnit.SECONDS).sample(5, TimeUnit.SECONDS).subscribe(getConsumer(tag));
}
//sample========aLong=======4 thread:===RxComputationThreadPool-1
//sample========aLong=======9 thread:===RxComputationThreadPool-1
//sample========aLong=======14 thread:===RxComputationThreadPool-1
//sample========aLong=======19 thread:===RxComputationThreadPool-1
//sample========aLong=======24 thread:===RxComputationThreadPool-1
//sample========aLong=======29 thread:===RxComputationThreadPool-1
//sample========aLong=======34 thread:===RxComputationThreadPool-1
//sample========aLong=======39 thread:===RxComputationThreadPool-1
//sample========aLong=======44 thread:===RxComputationThreadPool-1
//....public void throttleLast(String tag) {Disposable disposable = Observable.intervalRange(0, 100, 0, 1, TimeUnit.SECONDS).throttleLast(5, TimeUnit.SECONDS).subscribe(getConsumer(tag));
}
//throttleLast========aLong=======4 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======9 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======14 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======19 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======24 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======29 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======34 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======39 thread:===RxComputationThreadPool-5
//throttleLast========aLong=======44 thread:===RxComputationThreadPool-5
//....
这篇关于rxjava : 过滤操作符 : throttleFirst、sample/throwttleLast、throttleWithTimeout/debounce的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!