6

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.

ANUJ GUPTA
  • 905
  • 13
  • 22
  • Have you read https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0? – Mark Rotteveel Dec 23 '17 at 09:07
  • 1
    Yes i have read the documentation and i understand that they have introduced the concept of Disposable. I would just like a simple and easier to understand explanation. – ANUJ GUPTA Dec 23 '17 at 09:11
  • 1
    It literally says: _"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."_ That exactly answers your question. What part of that don't you understand? – Mark Rotteveel Dec 23 '17 at 09:12

1 Answers1

7

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

Community
  • 1
  • 1
Nouman Ch
  • 4,023
  • 4
  • 29
  • 42
  • Basically understand this, but what's with the sudden unexplained appearance of `ResourceSubscriber`? Are you saying that in your example, the `subscriber` in `.subscribeWith(subscriber)` must be a `ResourceSubscriber`? – Robert Lewis Dec 30 '17 at 02:04