Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Observable.defer and Observable.create in java rx

Tags:

java

reactivex

Can someone explain me the difference between defer and create methods in Observable? I failed to understand when I should use defer and when should I use create ..

REFERENCES:

Defer: http://reactivex.io/documentation/operators/defer.html

Create: http://reactivex.io/documentation/operators/create.html

Thank you

like image 537
Xitrum Avatar asked Mar 30 '16 15:03

Xitrum


People also ask

What is Observable defer?

defer allows you to create an Observable only when the Observer subscribes. It waits until an Observer subscribes to it, calls the given factory function to get an Observable -- where a factory function typically generates a new Observable -- and subscribes the Observer to this Observable.

What is defer in RxJava?

Android Online Course for Professionals by MindOrks Two important things to keep in mind: Defer does not create the Observable until the observer subscribes. Defer creates a fresh observable for each observer.

What is RX Observable?

There are two key types to understand when working with Rx: Observable represents any object that can get data from a data source and whose state may be of interest in a way that other objects may register an interest. An observer is any object that wishes to be notified when the state of another object changes.


1 Answers

So the distinction seems to be: defer is good when you have something that creates/returns an observable already, but you don’t want it to that process to happen until subscription.

create is good when you need to manually wrap an async process and create an observable. That creation is also deferred until subscription.

To put it another way:

defer is an operator that enables deferred composition of observable sequences.

create is a custom implementation of observable sequence (where creation is deferred until subscription).

So if you have a situation where you might use just to create an Observable from some results/value or you have a network API layer that returns an Observable of the request, but you don't want that request to kick off until subscription. defer would be good for those scenarios.

If you have a network API layer that doesn't return an Observable for a request, but which you need an Observable interface to, you might use create. That Observable sequence still wouldn't be created until subscription though. If you wanted that network call to kick off regardless of subscription, then you would use a different mechanism, like a Subject, potentially that replays.

like image 65
Bob Spryn Avatar answered Sep 17 '22 23:09

Bob Spryn