Return to site

ANGULAR INTERVIEW QUESTION: Explain the difference between Observables and Promises?

· ngInterview,fullstack

Let's start by defining each of them:

  • An Observable represents an asynchrone data stream. We import it from RxJS library.
  • A Promise is an Object which represents the state of an asynchronous operation which can be pending, done or rejected. Promises come natively with JavaScript since ECMAScript 6.

 

Now, let's discuss some of their differences:

 

1) Unique versus multiple value

An Observable is able to emit several values at once thanks to subscriptions:

 

If you take a time period, you can emit data along the way and you're not bound to only one value at some 't' instant. It helps representing more complex processes.

In the code above, we can have a data which is a static array and thanks to the asynchrone data stream, we can emit those data along the way in a time period.

Then you define a subscription once with the subscribe method and receive the array data.

While a promise can only emit one value.

Then the promise processing is considered over:

 

 

Each promise is able to provide only one value, so if the array is modified, you will have to call another time the promise to get the update.

 

 

2) Lazy vs eager

Observables are said 'Lazy'. It means that till we do not subscribe to a stream, nothing will be executed.

 

The code above does nothing till we trigger the subscribe method.

While a promise:

 

 

3) API strength of Observable

  • An observable can be canceled with 'unsubscribe' method, while a promise once executed can't be canceled
  •  

Observable have operators dealing complex operations, while a Promise has only one kind of use:

 

Observable are way more sophisticated than promises.

 

Conclusion

  • Observable can emit multiple data during a period while promises can emit only one value
  • Observables are lazy, while promises are executed straight away
  • Observables can be canceled, not promises
  • Observable have specific operators to handle data streams, but Promises do not