Observable and Observer
Explore the relationship between Observable and Observer in RxJava. Understand how to subscribe to Observables, manage events like onNext, onComplete, and onError, and grasp the synchronous and push-based nature of RxJava streams.
We'll cover the following...
An Observable can emit any number of items. As mentioned, to receive or listen to these emitted items, an Observer needs to subscribe to the Observable. The .subscribe() method is defined by the ObservableSource interface, which is implemented by Observable.
Once the Observable and Observer have been paired via the .subscribe() method, the Observer receives the following events through its defined methods:
- The
.onSubscribe()method is called along with aDisposableobject that may be used to unsubscribe from theObservableto stop receiving items. - The
.onNext()method is called when an item is emitted by theObservable. - The
.onComplete()method is called when theObservablehas finished sending items. - The
.onError()method is called when an error is encountered within theObservable. The specific error is passed to this method.
.Next()
The method .onNext() can be invoked zero, one, or multiple times by the Observable whereas the .onComplete() and ...