Konrad Viltersten Konrad Viltersten - 2 months ago 21
TypeScript Question

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

Answer Source

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

Observable.create is conventionally used in practice, probably because it reads better in chains and conforms other Observable static methods that are supposed to create a new observable, too.

The difference may appear in child classes. For example, Subject.create is not equal to new Subject and is supposed to be used regularly like Subject.create. 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.