So, after 2 years of using Angular, here are some things i found out:
- There is this library called RxJS - https://rxjs-dev.firebaseapp.com/guide/overview, which is written in TypeScript (superset of JavaScript). It is like one of thee best libraries for JavaScript.
Basically, it makes event-driven apps a breeze in JS by using the Observable
paradigm. A Promise
can only return a value once and is async only. Observables can be used to return a single value OR multiple values and can be sync or async (depending on how you use it), you can add pipes and operators to transform the results before it is used/consumed by the subscriber to it and etc; it gives a functional programming feel to using it, which is great. It is far more feature-rich than promises.
A subscriber
listens or "subscribes" to and Observable (the .subscribe()
call on an observable). An Observable emits 3 types of events: next
, error
, and complete
. Next means an event with/without data was emitted, error means there was an error within the event stream, and complete means the event stream has ended and the observable will not emit anymore.
Now, just because there was an error emitted, does not mean the event stream stopped. An event stream is only stopped when the complete event happens. Also, a subscriber can unsuscribe
from an observable, meaning it will stop listening to the event stream.
- The
HttpClient
service from Angular is built using RxJS. They basically wrapped it over the old XmlHttpRequest way of making requests - https://github.com/angular/angular/blob/main/packages/common/http/src/xhr.ts#L193.
When you make a request using Angular's HttpClient service, it automatically completes the observable on ok
response, so there is no needed to call unsuscribe on the observable since it's done anyway; it won't call complete on error response but http calls only response once.
- Observables don't execute until they are subscribed to; a Promise executes immediately.
I would say Observables are far better to use over Promises; i don't see RxJS leaving any time soon or ever.