Skip to main content

Promise vs Observable difference


Promise vs Observable difference

Promise

  1. It resolves or reject a single value and can handle a single value async task at a time.
  2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
  3. Not cancellable
  4. No rxjs support for operators. 
    read more about promise



Observable

  1. ability to emit multiple asynchronous values.
  2. Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
  3. Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
  4. Can be canceled using the unsubscribe method anytime.
  5. One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combine latest etc. to transform observable data before subscribing.

operation      observables Promise
creation
const obs= new Observable((observer) => {
    observer.next(5);
});

const promise= new Promise((resolve) => {
    resolve(5);
});
Subscribe
const sub= obs.subscribe(value => console.log(value));
promise.then(value => console.log(value));
unsubscribe
sub.unsubscribe();

   no cancellable

Comments