RxJava timer that repeats forever, and can be restarted and stopped at anytime

丶灬走出姿态 提交于 2019-12-04 23:14:44

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()
Anshuman

Call Observable.repeat() method to repeat

Disposable disposable = Observable.timer(3000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.newThread())
.repeat()
.observeOn(AndroidSchedulers.mainThread())
.subscribe();

If you want to stop it call disposable.dispose()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!