What is the difference between Promise
and Observable
in Angular?
An example on each would be helpful in understanding both the cases. In w
A Promise emits a single event when an async activity finishes or fails.
An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.
Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.
Promise: promise emits a single value
For example:
const numberPromise = new Promise((resolve) => {
resolve(5);
resolve(10);
});
numberPromise.then(value => console.log(value));
// still prints only 5
Observable: Emits multiple values over a period of time
For example:
const numberObservable = new Observable((observer) => {
observer.next(5);
observer.next(10);
});
numberObservable.subscribe(value => console.log(value));
// prints 5 and 10
we can think of an observable like a stream which emits multiple values 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 handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.
Promise:
Observable:
Angular Promises vs Observables