RxJava interval 操作符 取消订阅

时间:2023-01-12 14:45:17

interval会创建一个按照给定的时间间隔发射从0开始的整数序列的Observable,内部通过OnSubscribeTimerPeriodically工作。

  Observable.interval(1, TimeUnit.SECONDS)
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
//每隔1秒发送数据项,从0开始计数
//0,1,2,3....
}
});

取消订阅:


//Interval 取消订阅
private Long l;
private Subscription subscribe;
public void observable(){
subscribe = Observable.interval(2, TimeUnit.SECONDS)
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.e(TAG, "call: " + aLong );
l = aLong;
unSubscribe();
}
});

}

public void unSubscribe(){
//判断subscribe是否已经取消订阅 并且 l 的值已经等于3
if(!subscribe.isUnsubscribed() && l==3){
subscribe.unsubscribe();
}
}