25 Jun 2019

Observables vs Promises

Observable

  • Imagine an observable as a continuous stream of data.
  • You can subscribe to this stream and receive each item as it comes, and you can also perform various operations on these items.
  • The stream keeps flowing until you unsubscribe, and it can emit multiple items over time.
  • Observables are a technique used in reactive programming, a paradigm involving async data streams.
class Observable {
    constructor(functionThatTakesObserver) {
        this._functionThatTakesObserver = functionThatTakesObserver;
    }

    subscribe(observer) {
        return this._functionThatTakesObserver(observer)
    }
}

let myObservable = new Observable(observer => {
    setTimeout(() => {
        observer.next("Got data")
        observer.complete()
    }, 1000)
})

let myObserver = {
    next(data) { 
        console.log(data);
    },
    error(e) {
        console.log(e);
    },
    complete() {
        console.log("Request complete")
    }
}

myObservable.subscribe(myObserver)

// Output:
// (1 second) Got data
// (1 second) Request complete

Observables vs Promises

Everything you can do with a Promise you can do an Observable. Everything you can do with an observable you can’t necessarily do with a Promise. An observable can call next() multiple times, whereas a promise either resolves or rejects, it can’t emit multiple values.

Promise

  • Think of a promise as a one-time event that will happen in the future, like waiting for a package delivery.
  • You create a promise for a specific task, and it will either be fulfilled (success) or rejected (failure) when the task is completed.
  • Once the promise is fulfilled or rejected, it's done and can't change its outcome.
  • You can attach callbacks to handle the fulfillment or rejection of the promise.