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
....