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: wait till the observer subscribes before creating the Observable, and build a new Observable for each observer.
So, in this case, we’ll use an example to learn about RxJava’s Defer Operator. Assume we have a GfG class, as shown below:
We have two methods in the GfG class described above:
- getCourseObservable(): This function simply returns the Observable<String> by using Observable.just(course).
- getCourseDeferObservable(): The Observable<String> is returned by using Observable.just(course), but encased within the Observable defer().
Now, let’s test both methods and see what happens.
First, we’re going to make the price object. Then, using the price object, we use both the getCourseObservable and getCourseDeferObservable methods to retrieve the observables. Then we specify the course’s marque as “DSA.” Following that, we subscribe to both observables in order to determine the course’s price
The Output of the Above Code:
GfGExample: courseObservable : DEFAULT GfGExample: courseDeferObservable : DSA
Here, we can see that the courseObservable receives “DEFAULT” as the course’s name, but the courseDeferObservable receives “DSA” as the course. Because the defer operator was not used, courseObservable returns the old value “DEFAULT.” Because the defer operator was used, courseDeferObservable returns the most recent value, “DSA.” It indicates that Defer does not generate the Observable until the observer subscribes and that each observer receives a new Observable.
There are two critical points to remember:
- The Observable is not created until the observer subscribes.
- For each observer, Defer generates a new observable.
As a result, we may utilize the RxJava Defer Operator to solve the intriguing problem. Hope this article helped you to understand the topic!