Difference between Observable.defer and Observable

2020-06-07 04:01发布

问题:

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

回答1:

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.



回答2:

create(...) actually creates Observable immediately.

    public final static <T> Observable<T> create(OnSubscribe<T> f) {
        return new Observable<T>(hook.onCreate(f));
    }

defer(...) accepts Factory function that returns Observable(Subject, etc...), wraps it with OnSubscribeDefer and creates Observable only when subscriber subscribes, new Observable for every subscriber.

public final static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) {
    return create(new OnSubscribeDefer<T>(observableFactory));
}

See some more details here