RxJava计时器可以永久重复,并且可以随时重新启动和停止 [英] RxJava timer that repeats forever, and can be restarted and stopped at anytime
问题描述
在android中,我使用Timer执行任务,该任务每5秒重复一次,并以这种方式在1秒后开始:
In android i use Timer to execute task that repeats every 5 seconds and starts after 1 second in this way:
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()
this timer will repeat Until i call timer.cancel()
我正在学习具有RxAndroid扩展名的RxJava
I am learning RxJava with RxAndroid extension
所以我在互联网上找到了此代码,我尝试了它,但它不再重复了:
So i found this code on internet, i tried it and it doesnt repeat:
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计时器的替代方法是什么.
so what is the alternative for the android Timer in RxJava.
推荐答案
计时器运算符在指定的延迟后发出一个项,然后完成.我认为您正在寻找 interval 运算符.
timer operator emits an item after a specified delay then completes. I think you looking for the interval operator.
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
}
});
如果您想停止订阅,只需在订阅上取消订阅即可:
if you want to stop it you just call unsubscribe on the subscription:
subscription.unsubscribe()
这篇关于RxJava计时器可以永久重复,并且可以随时重新启动和停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!