1. 程式人生 > >RxJava 過濾操作符 sample

RxJava 過濾操作符 sample

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

....