Dedicated to the observer

In RxJava 1, which subscribes to Observer, a subscription has been returned that can be unsubscribed.

In RxJava 2, subscribing to Observer returns void and not Disposeable. How can I stop this "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 when we use an observer that itself does not 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 
+5
source share
1 answer

Everything else subscribe methods return a Disposable . In your example, TestObserver implements Disposable , so you can call dispose() on the observer itself to get rid of the subscription.

Otherwise, you can use DisposableObserver as a base class for your own observers, so that Disposable is provided to you by the base base class.

EDIT to answer the updated question:

If you need to use the subscribe(Observer) method (one that returns void), but you need to use an Observer that does not implement Disposable , you still have the option to wrap the Observer in SafeObserver , which will provide you with Disposable (among other guarantees of contract compliance) .

+8
source

Source: https://habr.com/ru/post/1262182/


All Articles