Types of Observables in RxJava
Last Updated :
23 Aug, 2022
In the model-view paradigm, this class represents an observable object, or "data." It can be subclassed in order to represent an object that the application wishes to watch. The issue is that you're creating software that will render data describing a three-dimensional scene in two dimensions. The application must be modular and allow for numerous, concurrent views of the same scene.
One or more observers can be assigned to an observable object. An observer can be any object that implements the Observer interface. When an observable instance changes, an application that calls the Observable's notifyObservers() method notifies all of its observers of the change through a call to their update method.
Image 1. The Observables in RxJava Explained.
In simple terms,
- An Observable is analogous to a speaker that broadcasts the value. It does various tasks and generates some values.
- An Operator is similar to a translator in that it converts/modifies data from one form to another.
- An Observer is what fetches the value.
Observable Types in RxJava
The many types of Observables in RxJava are as follows:
- Observable
- Flowable
- Single
- Maybe
- Completable
Let's commence creating some Observables in RxJava to better understand this,
Type #1: Creating a Basic Observable
Use Case: Assume you are downloading a file and need to push the current status of the download. You will have to emit more than one value in this case.
Kotlin
fun downloadObserervable(): Observable<Int> {
return Observable.create { gfgshooter ->
// Declaring an emitter in name of gfgshooter.
// Beginning the task (in this case a simple download)
// Your code...
if (!gfgshooter.isDisposed) {
// emit the progress
gfgshooter.onNext(20)
}
// Still Downloading
if (!gfgshooter.isDisposed) {
// send progress
gfgshooter.onNext(80)
}
// Progress 100, Download Over
if (!gfgshooter.isDisposed) {
// send progress
gfgshooter.onNext(100)
// send onComplete
gfgshooter.onComplete()
}
}
}
Type #2: Creating a Complex Obersever using Observable
Kotlin
fun getObserver(): Observer<Int> {
return object : Observer<Int> {
override fun onStart(d: Disposable) {
// Observation Started
// A sample editText
editText.setText("onStart")
}
override fun onNext(progress: Int) {
// Progress Updated
editText.setText("onNext : $progress")
}
override fun onError(e: Throwable) {
// Error Thrown
editText.setText("onError : ${e.message}")
}
override fun onComplete() {
// Observation Complete
editText.setText("onComplete")
}
}
}
Observer <> Flowable
When the Observable emits a large number of values that cannot be absorbed by the Observer, the Flowable comes into play. In this scenario, the Observable must skip some data based on a strategy, otherwise, it will throw an exception. A strategy is used by the Flowable Observable to handle the exception. BackPressureStrategy is the strategy, and MissingBackPressureException is the exception.
Geek Tip: Just like type #1, you can create Flowable using Flowable.create() similarly.
Solitary<> SingleObserver
When an Observable must emit only one value, such as a response to a network request, Single is used.
Type #3: Creating Single Observable
Kotlin
fun singleObservable(): Single<String> {
return Single.create { emitter ->
// any code which has a task
if (!gfgEmitter.isDisposed) {
gfgEmitter.onSuccess("Spandan's Code Ran!")
}
}
}
Then use it with a single observable in the following manner:
Kotlin
fun singleObservable(): SingleObserver<String> {
return object : SingleObserver<String> {
override fun onSubscribe(d: Disposable) {
edittext.setText("onStart")
}
override fun onSuccess(data: String) {
// Successfully Executed
editText.setText("onSuccess : $data")
}
override fun onError(e: Throwable) {
// Error or Exception thrown.
editText.setText("onError : ${e.message}")
}
}
}
The maybe <> Observer
When the Observable must emit a value or no value, maybe is used.
Type #4: Creating a maybe Observer
Kotlin
fun maybeObservable(): Maybe<String> {
return Maybe.create { gfgemitter ->
// your code goes here
if (!gfgemitter.isDisposed) {
gfgemitter.onSuccess("Spandan's Code!")
}
}
}
Completable <> CompletableObserver
When the Observable must do some job without emitting a value, it is called a Completable.
Type #5: Creating a Completable Observer
Kotlin
fun completeObservable(): Completable {
return Completable.create { gfgemitter ->
// your code here
if (!gfgemitter.isDisposed) {
gfgemitter.onComplete()
}
}
}
Using it now in the following manner:
Kotlin
fun completeObservable(): gfgObserver {
return object : gfgObserver {
override fun onStart(d: Disposable) {
// Started
editText.setText("Started")
}
override fun onError(e: Throwable) {
// Exception Thrown
editText.setText("onError : ${e.message}")
}
override fun onComplete() {
// Completed
editText.setText("Done")
}
}
}
Conclusion
The class combines the properties of a view (it textually shows the value of the model's current state) with a controller (it allows the user to enter a new value for the state of the model). With help of this article, you would have now known how to create an Observable in any way you want and then use it as your procured use case.
Similar Reads
Implement Search Using RxJava Operators Nowadays, most of the programs we use in our everyday lives include a search option that allows us to easily find what we're looking for. As a result, having a search tool is critical. And it is our job as developers to implement it better. Let's look at how to do it better with the RxJava Operators
4 min read
RxJava Defer Operator In this article, we will learn about the RxJava Defer Operator. Depending on our use case, we'll know when to utilize the Defer operator. We frequently make mistakes when utilizing the RxJava Defer Operator. Let's get this straight so we don't make a mistake. According to the documentation: Defer: w
2 min read
Scala AnyRef type The Scala kind hierarchy starts with Any, that's the supertype of all types. The direct subclasses of Any are AnyVal and AnyRef. Whereas AnyVal represents price kinds (which includes Int, Double, and so on.), AnyRef represents reference types. AnyRef serves because the fundamental type and root deta
3 min read
Introduction to RxJava RxJava is a powerful Java library designed for reactive programming. It simplifies the handling of asynchronous tasks and events by using observable streams. Reactive programming provides a clear and expressive way to work with events, data streams, and asynchronous processes. RxJava, being a part o
4 min read
LiveData vs ObservableField in Android LiveData helps to reduce memory leaks and manual lifecycle handling. It also ensures that UI is always up to date with the data even when the appâs activity is restarted while we are still using our app. It is a part of the architecture patterns of android. It is used for observing changes in the vi
4 min read