Tuesday, 5 September 2017

Different between promises and observables in angular 2

A Promise emits a single value where as an Observable emits multiple values over a period of time. You can think of an Observable like a stream which emits multiple items over a period of time and the same callback function is called for each item emitted. So with an Observable we can use the same API to handle asynchronous data whether that data is emitted as a single value or multiple values over a period of time.

A Promise is not lazy where as an Observable is Lazy. Let's prove this with an example. Consider this method getEmployeeByCode() in employee.service.ts. Notice this method returns an Observable.


As a quick summary, the differences are shown in the below.

Promise                                Observable
Emits a single value     Emits multiple values over a period of time
Not Lazy Lazy.                   An Observable is not called until we subscribe to the Observable
Cannot be cancelled    Can be cancelled using the unsubscribe() method
                                           Observable provides operators like map, forEach, filter, reduce, retry,                                                    retryWhen etc.

No comments:

Post a Comment