In RxJava 1 subscribing with an Observer returned a Subscription which could be unsubscribed.
In RxJava 2 subscribing with an Observer returns void and no Disposeable. How is it possible to stop that "Subscription"?
// v1
rx.Observable<Long> v1hot = rx.Observable.interval(1, TimeUnit.SECONDS);
rx.Observer<Long> v1observer = new TestSubscriber<>();
Subscription subscription = v1hot.subscribe(v1observer);
subscription.unsubscribe();
// v2
Observable<Long> v2hot = Observable.interval(1, TimeUnit.SECONDS);
Observer<Long> v2Observer = new TestObserver<>();
v2hot.subscribe(v2Observer); // void
EDIT: how to handle the case, where we use an observer which doesn't itself implement Disposable
, like BehaviorSubject
? Like in this example:
// v1
rx.Observable<Long> v1hot = rx.Observable.interval(1, TimeUnit.SECONDS);
rx.Observer<Long> v1observer = rx.subjects.BehaviorSubject.create();
Subscription subscription = v1hot.subscribe(v1observer);
subscription.unsubscribe();
// v2
Observable<Long> v2hot = Observable.interval(1, TimeUnit.SECONDS);
Observer<Long> v2Observer = BehaviorSubject.createDefault(-1L);
v2hot.subscribe(v2Observer); // void
It is good practice to dispose complete observable chain running in your Activity or Fragment Life-Cycle. A typical example of disposing an Observable: In above example, you can see that in doTask() method, disposable is added to CompositeDisposable and in onStop observable is disposed using compositeDisposable.
Disposables are streams/links/connections between Observer and Observable . They're meant to give power to the Observers to control Observables . In most cases, the Observer is a UI element, ie; Fragment , Activity , or a corresponding viewmodel of those elements.
The CompositeDisposable class represents a container which can hold multiple disposable and offers O(1) complexity of adding and removing disposables.
An Observable is like a speaker that emits a value. It does some work and emits some values. An Operator is like a translator which translates/modifies data from one form to another form. An Observer gets those values.
All other subscribe methods return a Disposable
. In your example, the TestObserver
itself implements Disposable
, so you can call dispose()
on the observer itself to dispose of the subscription.
Otherwise you can use DisposableObserver
as a base class for your own custom observers to have the Disposable
behavior provided to you by the abstract base class.
EDIT to answer the updated question:
In case you need to use the subscribe(Observer)
method (the one returning void), but you need to use an Observer
which doesn't implement Disposable
, you still have the option to wrap your Observer
in a SafeObserver
which will provide you with Disposable
behavior (among other contract conformance guarantees).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With