Android RxJava 创建操作符Interval

时间:2022-05-16 17:51:20

Interval操作符:用于创建Observable,跟TimerTask类似,用于周期性发送信息,是一个可以指定线程的TimerTask

首先添加类库

    // RxAndroid
compile 'io.reactivex:rxandroid:1.2.1'
// RxJava
compile 'io.reactivex:rxjava:1.2.4'

(1) 间隔时间3秒发送一次

    private Subscription subscribe;
private void start() {
if (subscribe == null || subscribe.isUnsubscribed()) {
subscribe = Observable.interval(3000, 3000, TimeUnit.MILLISECONDS)//延时3000 ,每间隔3000,时间单位
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.e("1234", "执行一次");
}
});
}
}

(2)取消订阅

private void stop() {
if (subscribe != null && !subscribe.isUnsubscribed()) {
subscribe.unsubscribe();
Log.e("1234", "停止");
}
}