Skip to content

Instantly share code, notes, and snippets.

@kousherAlam
Last active January 7, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kousherAlam/205621bab701674eed84cc08dc2099b3 to your computer and use it in GitHub Desktop.
Save kousherAlam/205621bab701674eed84cc08dc2099b3 to your computer and use it in GitHub Desktop.

Observer and promises in javascript

The main defference between observable and promises is:

1. observer can emit multiple value, but promise only can work with single value. when promise `reject` or `resolve` they end.
2. promise is **eager** but observer are **lazy**
3. Promise are not cancelable but observable are cancelable 
4. Promises are always asynchronous but obervable are possibly asnychronous.
5. Promise are always multicast but Observable are both multicase and unicast

example:

Observer

const interval = new Observable(observer => {
  let count = 0;
  const interval = setInterval(() => {
    observer.next(count++);
  }, 1000);

  // once we stop listening to values clear the interval
  return () => {
    clearInterval(interval);
  }
});

interval.subscribe(value => console.log(value));

Promise

const promieInterval = new Promise((resolve, reject)=>{
    let count = 0;
    const interval = setInterval(()=>{
        resolve(count);
        // or 
        reject(count);
    }, 1000);
});

Promise are multicast

Observable are either multicast or unicast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment