arching
arching

Reputation: 85

About the usage of the subscribeWith method with returning Subscriber

I wonder why the subscribeWith method returns Subscriber but not strictly Disposable or maybe Subscription.

I think that the subscribeWith method were designed for the usage of RxJava 1.x's subscribe method which returns Subscription. Therefore, in 2.0, I think that the main usage of subscribeWith method would be the use with the Subscriber which implements Disposable.

Howerver, since the subscribeWith method can return a Subscriber, Subject-like usage (such as the below code) can be possible.

Subscriber<Long> subscriber = Flowable.interval(100, TimeUnit.MILLISECONDS)
    .subscribeWith(new Subscriber<Long>() {
      ...
    });

...

subscriber.onNext(999);

...

Is this OK or something that I should not do?

Upvotes: 2

Views: 4387

Answers (2)

Ajay Deepak
Ajay Deepak

Reputation: 471

if you have a same observer that you want to bind to different observable, use .subscribeWith ,so multiple Observables can use the same observer implementation.

Upvotes: 0

akarnokd
akarnokd

Reputation: 69997

Subscriber in 2.x doesn't implement Disposable and would require wrapping/hijacking every Subscriber. You get back what you subscribed with and we have ResourceSubscriber and DisposableSubscriber that specifically implement Disposable in a correct way.

Howerver, since the subscribeWith method can return a Subscriber, Subject-like usage (such as the below code) can be possible.

This is not recommended as you violate the protocol by possibly calling onNext concurrently. (This is not the result of subscribeWith because you could pre-create the Subscriber, call subscribe() and then call onNext() on the original Subscriber instance violating the protocol the same way.)

subscribeWith is indeed there to work with subscribers that support Disposable in a fluent manner and allow the following pattern:

CompositeDisposable cd = new CompositeDisposable();

cd.add(source.subscribeWith(new ResourceSubscriber<Integer>() { ... }));

See our wiki for this and other 2.x details.

Upvotes: 6

Related Questions