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.
observeOn() simply changes the thread of all operators further Downstream. People usually have this misconception that observeOn also acts as upstream, but it doesn't. subscribeOn() only influences the thread which is going to be used when Observable is going to get subscribed to and it will stay on it downstream.
The subscribe function returns a Subscription object that allows us to manage the created relationship between the observable and the subscriber. “Us” in this context is the creator of the logic—the observables and subscribers are building blocks at our disposal.
The Subscribe operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable, or to receive error or completed notifications from the Observable, it must first subscribe to that Observable with this operator.
Flowable: emit a stream of elements (endlessly, with backpressure) Single: emits exactly one element. Maybe: emits zero or one elements. Completable: emits a “complete” event, without emitting any data type, just a success/failure.
Since 1.x
Observable.subscribe(Subscriber)
returnedSubscription
, users often added theSubscription
to aCompositeSubscription
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 EsubscribeWith
(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 sinceResourceSubscriber
implementsDisposable
directly:CompositeDisposable composite2 = new CompositeDisposable(); composite2.add(Flowable.range(1, 5).subscribeWith(subscriber));
Source: What's different in [RxJava] 2.0
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