Observables vs Promise in Angular

Hello Everyone,

Back again with a new article where we will look into differences of observable and promise,

In angular to deal with asynchronous data operations, we use promises or observables. In angular, both Get and Post methods of Http and HttpClient by default returns an observable.

Promise emits a single value whereas the observable emits multiple values over a period of time. We can think of observable as a stream of data that calls the same callback method.

Let’s just look at the internal structure for promise call,

Promise in angular

So if you look in the promise method definition we got a two-parameter onfulfilled is called when the request which is made is executed successfully. If there is a problem with the request which is made then an onrejected callback is called.

Now that we have checked the promise method details let’s just look for the observable subscribe method,

Observable in angular

Here subscribe method got three parameters next, error, and complete. As observable emits the vales over a period of time so next callback is called for getting each value. When the last item is emitted and handled the complete callback is called. If there is an error while processing the request then an error callback is called.

Examples of observable and promise are below,

const numberPromise = new Promise((resolve, reject) => {resolve(10);resolve(20);})numberPromise.then(value => console.log(`Promise ${value}`));const numberObservables = new Observable(observer => {observer.next(10);observer.next(20);});numberObservables.subscribe(value => console.log(`Observables ${value}`));
Example Output

Another difference between promise and observable is the promise is not lazy and observable is not lazy means it’s not called until we subscribe to the observable.

The promise can not be canceled once the request is made and observable can be canceled using unsubscribe() method.

Thank You, See you in the next article !!

You can reach out or connect to me over here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *