之前有写过Android实现倒计时之使用CountDownTimer,除了CountDownTimer,开发中我们也会用到handler,例如
mHandler.sendEmptyMessageDelayed(1, 10*1000);
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("流程", "10秒时间已到");
}
};
现在结合RxJava来的Observable.timer操作符,既可以延迟执行一段逻辑,也可以间隔执行一段逻辑
(1)Timer 延迟10秒执行:
private void timer() {
Observable.timer(10000, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.e("流程", "10秒倒计时已结束");
}
});
}
(2)Timer 间隔1秒执行:
private Subscription subscribe;
private void timer() {
subscribe= Observable.timer(1000,1000,TimeUnit.MILLISECONDS).subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
Log.e(TAG, "------>along:"+aLong+" time:"+ SystemClock.elapsedRealtime());
}
});
}
记得要取消订阅
private void stop() {
if (subscribe != null && !subscribe.isUnsubscribed()) {
subscribe.unsubscribe();
}
}
网友评论