使用 RXAndroid 的可停止背景 timer/observable

Stoppable background timer/observable with RXAndroid

我正在尝试使用 RXAndroid 创建一个重复的后台计时器。我已经编写了在后台以指定时间间隔执行的代码,但我找不到停止它的方法。

Observer<Long> observer = new Observer<Long>() {
        @Override
        public void onSubscribe(Disposable d) {}

        @Override
        public void onNext(Long aLong) {

            Log.d(LOGTAG, "Interval:" +String.valueOf(aLong));
        }

        @Override
        public void onError(Throwable e) {}

        @Override
        public void onComplete() {}
    };


    Observable observable = Observable.interval(1, 1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io());

    observable.subscribe(observer);

我想知道请问:

  1. 这是在 RXAndroid 中创建 "timer" 以在后台定期执行代码的正确方法吗?
  2. 我该如何阻止它?
  1. Is this the correct approach for creating a "timer" in RXAndroid to execute code periodically in the background?

是的,

  1. How do I stop it?

要在 RxJava 中取消观察者,您必须使用 Disposable 的引用。

您可以在 onSubscribe(Disposable d).

中找到

onSubscribe() 将在您订阅 observable 时调用。在你的情况下是 observable.subscribe(observer).

在观察者中,您有方法 public void onSubscribe(Disposable d) {},它将提供 Disposable 的参考。 声明 Disposable 的全局实例,并且每当你想取消调用 Disposable::dispose().