How to subscribe and unsubscribe or cancel an rxjava observable

对着背影说爱祢 提交于 2019-12-07 18:05:27

Why am I getting false in onSubscribe() of SingleObserver getSingleObserver() .

You're currently logging whether the disposable is disposed within the onSubscribe method. At this point the disposable hasn't been disposed yet.

How do I unsubscribe or cancel the observable/observer when activities onStop() is called.

Rather than use a SingleObserver you could use the subscribe method which returns a disposable. With this you could either manage the disposable directly or use a CompositeDisposable. You would then call the dispose method on that disposable, with CompositeDisposable this is achieved by calling clear()

private final CompositeDisposable disposables = new CompositeDisposable();

@Override
protected void onStart() {
    super.onStart();
    disposables.add(getSingleObservable()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(value -> {
                Log.d(TAG, " onSuccess: " + value);
            }, error -> {
                Log.e(TAG, " onError", error);
            }
        )
    );
}

@Override
protected void onStop() {
    disposables.clear();
    super.onStop();
}

Also, what really happens when screen oriantation. Does the observable get unsubscribed automatically or it continues its work ? what to do for the device rotation ?

By default no automatic management of the observable occurs, it's your responsibility to manage it. In your example code when the device rotates you will receive another call to onCreate, here you're scheduling the work to be executed again, work that was scheduled before rotation could still be running, so you could end up leaking the old activity and receiving a callback when the work succeeds or fails - in this case you'd see a log statement.

There are some tools that provide automatic observable management, though you should read the authors article about some of the issues that exist with this approach.

Another option for you could be to look at the new Architecture Components library, specifically ViewModel and LiveData. This will simplify what you need to do with respect to subscription management and configuration changes.

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