RxJava 過濾操作符 sample
阿新 • • 發佈:2019-02-05
sample操作符是定期掃描源Observable產生的結果,在指定的間隔週期內進行取樣
例子1:每2s掃描一次
結果:Observable.interval(1, TimeUnit.SECONDS).sample(2, TimeUnit.SECONDS).subscribe(new Observer<Long>() { @Override public void onCompleted() { LogUtils.d("-------->onCompleted()"); } @Override public void onError(Throwable e) { LogUtils.d("-------->onError()" + e); } @Override public void onNext(Long aLong) { LogUtils.d("-------->onNext()" + aLong); } });
03-02 09:36:08.722 8623-8768/com.rxandroid.test1 D/----->: -------->onNext()0
03-02 09:36:10.722 8623-8768/com.rxandroid.test1 D/----->: -------->onNext()2
03-02 09:36:12.722 8623-8768/com.rxandroid.test1 D/----->: -------->onNext()4
03-02 09:36:14.722 8623-8768/com.rxandroid.test1 D/----->: -------->onNext()6
.....
注意這裡會預設開啟一個新執行緒,我們也可以指定執行緒
結果:Observable.interval(1, TimeUnit.SECONDS).sample(2, TimeUnit.SECONDS, Schedulers.newThread()).subscribe(new Observer<Long>() { @Override public void onCompleted() { LogUtils.d("-------->onCompleted()"); } @Override public void onError(Throwable e) { LogUtils.d("-------->onError()" + e); } @Override public void onNext(Long aLong) { LogUtils.d("-------->onNext()" + aLong + " thread:" + Thread.currentThread().getName()); } });
03-02 09:43:25.582 15427-15698/com.rxandroid.test1 D/----->: -------->onNext()0 thread:RxNewThreadScheduler-2
....