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.).
Observable are just that — things you wish to observe and take action on. Angular uses the Observer pattern which simply means — Observable objects are registered, and other objects observe (in Angular using the subscribe method) them and take action when the observable object is acted on in some way.
An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.
Observables are not executed until a consumer subscribes. The subscribe() executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time.
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.
The two are interchangeable, but the inline documentations says that Observable.create
is deprecated (future proof link here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With