从循环中停止Observable

时间:2017-05-29 07:11:02

标签: android rx-java rx-java2

最近我一直在研究RxJava 2并测试了 Observable.interval()

subscription = Observable.interval(1, TimeUnit.MILLISECONDS, Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

subscription.subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long aLong) {
                //binding.appBar.mainContent.msg.setText(aLong+"");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

在活动的onCreate方法之后启动Observable。我通过onNext()方法记录输出。我有一个停止按钮。当它被触发时我想停止订阅流程。

即使单击停止按钮,日志也会继续。

stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (subscription != null) {
                    subscription.unsubscribeOn(Schedulers.io());
                }
            }
        });

1 个答案:

答案 0 :(得分:2)

您订阅了Observer,这意味着您必须保留对来自Disposable回调的实际onSubscribe(Disposable)的引用,然后对该对象执行Disposable#dispose()



    private Disposable disposable;

    ...

    Observable.interval(1, TimeUnit.MILLISECONDS, Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Observer() {
              @Override public void onSubscribe(Disposable d) {
                disposable = d;
              }

            // other callbacks here

            });

    disposable.dispose();


相反,您可以将订阅更改为以下内容:



    Disposable disposable = Observable.interval(1, TimeUnit.MILLISECONDS, Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer() {
          @Override public void accept(Long aLong) throws Exception {
            // onNext
          }
        }, new Consumer() {
          @Override public void accept(Throwable throwable) throws Exception {
            // onError
          }
        }, new Action() {
          @Override public void run() throws Exception {
            // onComplete
          }
        });

    disposable.dispose();