Konrad Viltersten
Konrad Viltersten

Reputation: 39190

Difference between new Observable(...) and Rx.Observable.create(...)?

I'm updating our software substituting all promises (and other hairy junk) for observables. To make sure that I'm following best practices, I made a quick googlearch and noticed that in some cases, the suggested syntax is by instance whereas in other cases, the examples perform a call by factory.

const byInstance = new Observable(_ => { ... });

const byFactory = Rx.Observable.create(_ => { ... });

I'm curious what's the actual difference. Are they precisely interchangeable? Is it an older/newer syntax/approach? Is it framework related? And, of course, which is to be preferred (under the condition that it's not opinionated, disputed etc.).

Upvotes: 33

Views: 7030

Answers (2)

Mathieu CAROFF
Mathieu CAROFF

Reputation: 1502

The two are interchangeable, but the inline documentations says that Observable.create is deprecated (future proof link here).

Upvotes: 6

Estus Flask
Estus Flask

Reputation: 222760

There is no difference. Observable.create calls new Observable.

As the manual says,

Observables are created using Rx.Observable.create or a creation operator

<...>

Rx.Observable.create is an alias for the Observable constructor

Observable.create is conventionally used, probably because it reads better in chains and conforms with other Observable static methods that create observables, too.

The difference may appear in child classes. For example, Subject.create is equal to AnonymousSubject.create and not equal to new Subject. Usually Subject.create is the one that provides desirable behavour, while new Subject is more low-level. This confirms the point about the convention.

On the other hand, some classes (notably BehaviorSubject) are supposed to be used with new because create signature doesn't allow to provide the desired behaviour to them.

Upvotes: 28

Related Questions