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

18,729

Solution 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.

Solution 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

Share:
18,729
Xitrum
Author by

Xitrum

merge me

Updated on July 12, 2022

Comments