Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
ANUJ GUPTA Avatar asked Dec 23 '17 09:12

ANUJ GUPTA


People also ask

What's the difference between observeOn() and subscribeOn()?

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.

What is subscribe in RxJava?

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.

What is subscribe in reactive programming?

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.

What is flowable in RxJava Android?

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.


1 Answers

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

like image 169
Nouman Ch Avatar answered Oct 11 '22 01:10

Nouman Ch