Observable vs Promise | Which is Better?

Observable vs Promise | What's the difference?
Observable vs Promise | Which is better?
Observable vs Promise | When to use Promise
Observable vs Promise | When to use Observable

Both the Promise and Observable are used to handle async activity in JavaScript. While an Observable can do everything a Promise can, the reverse is not true.

For example, an Observable can emit multiple values over time. A Promise only resolves once.

This may lead you to believe that the Observable is BETTER than the Promise. After all, if an Observable can do everything a Promise can then why even bother using the Promise at all?

Like many programming questions, the answer isn't straightforward. Choosing one over the other requires context. Both have their strengths and weaknesses. Here are some reasons why you would consider using a Promise over an Observable and vis-versa.

Observables aren't native to JavaScript

Observables are really just objects that notify observers about change in state. Observers are implementations of the observer design pattern. While you can implement observables yourself, the RxJs implementation is more commonly used...

import { Observable } from 'rxjs'
let myObservable = new Observable()

Notice how we have to import from the rxjs library to use the RxJS Observable.

With the release of ES6, the Promise is native to JavaScript...

let myPromise = new Promise((reject, resolve) => resolve(1))

You don't need to import any libraries. Promises just work!

If you don't want to rely on third party libraries like RxJs then use Promises to handle async activity.

A Promise can't be canceled

You can cancel an observable by unsubscribing. You can't cancel a Promise.

If you want the ability to cancel an async activity use observables. If you always want to handle the completion of a single event use promises.

Observables can emit multiple values

Observables emit streams of data over time. Promises reject/resolve a single event. An Observable will emit events where a defined callback executes for each event.

If you want to handle a single event, use a Promise. If you want to stream multiple events from the same API, use Observables.

Conclusion

Observables can do everything Promises can. Additionally, Observables are "cancellable" and can emit multiple events whereas Promises reject/resolve a single event.

While Observables are seemingly "better" for any use case, there are times where a Promise is more appropriate, especially when your application is async by nature.

Your thoughts?