Understanding RxJava Defer Operator

In this blog, we are going to learn the RxJava Defer Operator. We will understand when to use Defer operator depending on our use-case. Most of the time, we do mistake while using the RxJava Defer Operator. Let's understand it clearly to avoid the mistake.

As per documentation:

Defer: do not create the Observable until the observer subscribes, and create a fresh Observable for each observer

So here, we will be taking an example to learn the Defer Operator of RxJava.

Let say we have a class Car as below:

class Car {

    var brand: String = "DEFAULT"

    fun getBrandObservable(): Observable<String> {
        return Observable.just(brand)
    }

    fun getBrandDeferObservable(): Observable<String> {
        return Observable.defer {
            return@defer Observable.just(brand)
        }
    }

}

In the above Car class, we have two methods as below:

  • getBrandObservable(): It returns the Observable<String> by just using Observable.just(brand).
  • getBrandDeferObservable(): It returns the Observable<String> by using Observable.just(brand) but wrapped inside the Observable.defer().

Now, let's try to use both the method and see the difference.

val car = Car()

val brandObservable = car.getBrandObservable()
val brandDeferObservable = car.getBrandDeferObservable()

car.brand = "BMW"

brandObservable
.subscribe { brand ->
    Log.d("DeferExample", "brandObservable : $brand")
}

brandDeferObservable
.subscribe { brand ->
    Log.d("DeferExample", "brandDeferObservable : $brand")
}

Here, first, we are creating the car object. Then using the car object, we are calling both the methods which are getBrandObservable and getBrandDeferObservable to get the observables. Then, we are setting the brand of car as "BMW". After that, we are subscribing to both the observables to get the brand of the car.

It will print the following:

DeferExample: brandObservable : DEFAULT
DeferExample: brandDeferObservable : BMW

Here we can see that the brandObservable is getting the "DEFAULT" as the brand of the car and the brandDeferObservable is getting "BMW" as the brand of the car.

brandObservable is returning the old value which is "DEFAULT" as it has not used the defer operator.

brandDeferObservable is returning the latest value which is "BMW" as it has used the defer operator.

It means that Defer do not create the Observable until the observer subscribes, and create a fresh Observable for each observer.

Two important things to keep in mind:

  • Defer do not create the Observable until the observer subscribes.
  • Defer create a fresh observable for each observer.

This way we can use RxJava Defer Operator to solve the interesting problem.

Find the complete project here and learn RxJava.

Happy Learning :)

Team MindOrks

Also, Let’s become friends on Twitter, Linkedin, Github, Quora, and Facebook.