DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Jinto Jose
Jinto Jose

Posted on • Updated on

RxJS - Promise vs Observable

One basic question which first comes to mind when we have been using Promises and then, trying to move to Observables... is why to use Observable instead of Promise.

Since Angular started utilizing RxJS everywhere, Observables became more and more popular. But, confusion comes when we are just making an api call using HttpClient and this returns Observable. We wonder, I can do the same in promise.

I am trying to answer that with an example.

Let's first try to create a Promise and an Observable which just finishes with one value.


const s = new Observable(observer => {
   setTimeout(() => {
     observer.next('hi');
   }, 100);
});

s.subscribe(value => {
   console.log(value);
});

const p = new Promise((resolve, reject) => {

setTimeout(() => {
  resolve('hi');
}, 100);

});

p.then((value) => {
  console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

In this scenario, there is not much difference between Observable and Promise except that, we are using .subscribe instead of .then.

But, what if there are two values. Let's see the code for that.

const s = new Observable(observer => {
  setTimeout(() => {
    observer.next('hi');
  }, 100);
  setTimeout(() => {
    observer.next('hello');
  }, 200);
});

s.subscribe(value => {
  console.log('observable:', value);
});

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('hi');
  }, 100);

  setTimeout(() => {
    resolve('hello');
  }, 200);
});

p.then(value => {
  console.log('promise: ', value);
});
Enter fullscreen mode Exit fullscreen mode

In this scenario, there are two values being emitted, and you can see that, promise is not considering the second value which is resolved. For a promise, it is one asynchronous operation, and that is completed at the first resolve execution itself.

But, in case of Observable, subscriber keeps listening for the new data, until the observer says completed.

Hope the difference is clear now.

Latest comments (1)

Collapse
 
frontendtony profile image
Anthony Oyathelemhi

Hey @jintoppy , this is clear and straight to the point, without all the unnecessary gibberish people write to look smart

Thank you

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await