Open In App

Types of Observables in RxJava

Improve
Improve
Like Article
Like
Save
Share
Report

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.

 



Last Updated : 23 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads