Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

rx java - 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?

question from:https://stackoverflow.com/questions/65626693/laziness-with-rxjava-defer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...