Observables vs Promises
Asynchronous programming in JavaScript can be achieved by using - Callbacks, Promises, async/await, RxJs Observables
Observables are used to transfer messages between publishers and subscribers in your applications. Observables are a part of RxJs(Reactive extensions for javascript) which is a library for reactive programming using observables.
Angular uses observables for a lot of asynchronous programming and event handling. For example,
- For transmitting data between components - EventEmitter extends RxJs Subject and exposes a emit() method to send values to the subscribers.
- Angular HTTP Module uses observables to handle AJAX requests and responses - Angular Httpclient returns an observable when making HTTP calls ex. http.get('URL') returns an observable. Few Advantages are the requests can be cancelled through the unsubscribe method, failed requests are retired easily)
- The ROUTER and FORMS module use observables to listen and respond to user input events - Router.events, ActivatedRoute, Reactive forms ValueChanges and statuschanges all use observables
- AsyncPipe - It uses observables to notify of any changes through the next call {{ time | async}}
Promises - with promises the executing function returns a promise and you tell the promise what to do when an asynchronous call completes/fails.
Often Observables are preferred over Promise because it provides the features of promise and much more. Let's see the difference between observables and promises.
Promises emit a single value. (Has only two callback functions (resolve and reject)).
Observables emit multiple values over a period of time. (Subscribe method has three callback functions (next, complete, error) next callback if emitted as and when you receive data/values).
A promise handles a single event when an asynchronous operation completes or fails.
An observable is like a stream and allows to pass zero or more events when the callback is called for each event. It doesn't matter if you want to handle one or multiple events, you can use the same API in each case.
Promises are not cancellable and the promise will eventually call the success or failed callback even when you don't need the notification or result it provides anymore.
Observables are cancelable and if the result of an expensive async HTTP call isn't needed anymore, the subscription of the observable allows to cancel the subscription.
Promises are eager and are executed immediately.
Observables are not eager and are only executed when subscribed to.
Additionally, Observables provide a lot of powerful operators like map, forEach, filter, reduce, retry, retryWhen etc.
Additionally, Observables provide a lot of powerful operators like map, forEach, filter, reduce, retry, retryWhen etc.
Comments
Post a Comment