RxJava计时器可以永久重复,并且可以随时重新启动和停止

MBH*_*MBH 16 android observer-pattern rx-java rx-android

在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();
Run Code Online (Sandbox Code Playgroud)

这个计时器将重复直到我打电话 timer.cancel()

我正在学习RxAava并使用RxAndroid扩展

所以我在互联网上找到了这个代码,我尝试了它并且它没有重复:

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
        }
    });
Run Code Online (Sandbox Code Playgroud)

那么什么是RxJava中的Android定时器的替代品.

小智 38

计时器操作员在指定的延迟后发出一个项目然后完成.我想你在找间隔算子.

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
                }
            });
Run Code Online (Sandbox Code Playgroud)

如果您想要停止它,您只需在订阅上调用取消订阅:

subscription.unsubscribe()
Run Code Online (Sandbox Code Playgroud)

  • 你不需要`.subscribeOn(Schedulers.io())`在后台启动,因为默认情况下`Observable.interval`会在`Schedulers.computation()`上发出. (21认同)
  • 在 RX 2 而不是 Action1 你应该使用 Consumer (4认同)

小智 7

Observable.repeat()重复调用方法

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

如果您想停止通话 disposable.dispose()