Reputation: 7524
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
Reputation: 70017
Because someBlockingMethodTofetchDBRecords
is not lazy and you hand its result to an Observable
after.
Yes, Observable
s 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