在 android 中,我使用 Timer 以这种方式执行每 5 秒重复一次并在 1 秒后开始的任务:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Here is the repeated task
}
}, /*Start after*/1000, /*Repeats every*/5000);
// here i stop the timer
timer.cancel();
这个计时器会重复直到我调用timer.cancel()
我正在学习带有 RxAndroid 扩展的 RxJava
所以我在网上找到了这段代码,我试了一下,但没有重复:
Observable.timer(3000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
// here is the task that should repeat
}
});
那么在 RxJava 中 android Timer 的替代方案是什么。
最佳答案
timer 运算符在指定的延迟后发出一个项目然后完成。我认为您正在寻找 interval 运算符。
Subscription subscription = Observable.interval(1000, 5000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
public void call(Long aLong) {
// here is the task that should repeat
}
});
如果你想停止它,你只需在订阅上调用取消订阅:
subscription.unsubscribe()
关于android - RxJava 定时器,永远重复,可以随时重启和停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38605090/