Mandroid
Mandroid

Reputation: 7524

Laziness with RxJava defer

I am going through a book which tells how to intorduce RxJava in legacy blocking code.

It basically does this:

Observalbe.defer(() -> {return Observable.from(someBlockingMethodTofetchDBRecords(....))});

It says that defer would introduce laziness in the program. But isn't Observable by default lazy. Observable.from should return an observable and it wont do anything until we subscribe to it. So why do we need defer here?

Upvotes: 0

Views: 281

Answers (1)

akarnokd
akarnokd

Reputation: 70017

Because someBlockingMethodTofetchDBRecords is not lazy and you hand its result to an Observable after.

Yes, Observables are lazy by default thus they don't perform their subscription action until there is an Observer subscribing. However, from's subscription action is to iterate over an existing sequence and emit its values. That sequence was handed, and thus created, outside of Observable.

Therefore, if you need to have the sequence itself to be created only when there is an Observer for it, its creation has to be part of the subscription action, for which defer is an operator to make that happen.

Upvotes: 2

Related Questions