ANUJ GUPTA
ANUJ GUPTA

Reputation: 925

What is the difference between subscribe() and subscribeWith() in RxJava2 in android?

What is the difference between subscribe() and subscribeWith() in RxJava2 in android? Both function are used to subscribe an Observer on an Observable. What is the major difference between the two function ?. Where to use subscribe and where to use subscribeWith. If possible please provide code samples.

Upvotes: 6

Views: 4563

Answers (1)

Nouman Ch
Nouman Ch

Reputation: 4121

Since 1.x Observable.subscribe(Subscriber) returned Subscription, users often added the Subscription to a CompositeSubscription for example:

CompositeSubscription composite = new CompositeSubscription();

composite.add(Observable.range(1, 5).subscribe(new TestSubscriber<Integer>()));

Due to the Reactive-Streams specification, Publisher.subscribe returns void and the pattern by itself no longer works in 2.0. To remedy this, the method E subscribeWith(E subscriber) has been added to each base reactive class which returns its input subscriber/observer as is. With the two examples before, the 2.x code can now look like this since ResourceSubscriber implements Disposable directly:

CompositeDisposable composite2 = new CompositeDisposable();

composite2.add(Flowable.range(1, 5).subscribeWith(subscriber));

Source: What's different in [RxJava] 2.0

Upvotes: 7

Related Questions