Observable v/s Promise in Angular

Reading Time: 3 minutes

Introduction

We must have worked with both these concepts – Promise and Observable or must have heard about them. However, we might get confused about which one to use when. To avoid this confusion we must be knowing about the differences so that we can choose the appropriate one for our situation. It all depends on your use case and which one to choose. So let us have a look at the differences.

Observable v/s Promise

Emitting Values

The first difference is that an Observable can emit multiple values. On the other hand, Promises emit only a single value. Here we will look at this difference in the example mentioned below.

const testObservsable = Observable.create( observer => {
 	observer.next( '1' )
 	observer.next( '2' )
 	observer.next( '3' )
 	observer.complete()
   })
 
testObservable.subscribe(val => 
              console.log(val),
              error=> console.log("error"),
              () => console.log("complete"))
}

Here we are creating an observable while will emit the values 1, 2, and 3. And then we subscribe to it.

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("done"), 1000);
});

We have created a simple promise that after 1 second will signal that job is done with the result as “done”.

Cancelable Subscriptions in Observable

We have a subscription that can be canceled in Observables but Promises cannot be canceled. The subscription allows us to stop the listener from receiving more values.

In an observable, we have different ways of canceling it. Here are those methods:

  • Unsubscribe – It cancels the subscription from the observable.
const observable = interval(1000);
const subscription = observable.subscribe(x => console.log(x));
subscription.unsubscribe();
  • take – The take operator accepts a number and takes only those number of elements from the observable and cancels the subscription.
const values$ = interval(1000);
const result = values$.pipe(take(5));
const subscribe = result.subscribe(val => console.log(val));

Since here in this example we have 5 as an argument in take so it will take the first 5 emitted values and will output 0, 1, 2, 3, 4

  • takeUntil – this operator takes the values until the observable emits any value.
const source = interval(1000);
//after 5 seconds, emit value
const timer$ = timer(5000);
//when timer emits after 5s, complete source
const example = source.pipe(takeUntil(timer$));
//output: 0,1,2,3
const subscribe = example.subscribe(val => console.log(val));

It will emit a value after 5 seconds and after that complete source. So the output values will be 0,1,2,3

Lazy & Eager

The other difference is that observables are considered as lazy as they are not executed until we subscribe to them and Promises are not lazy because they execute after the creation. We need not subscribe to promises. Promises are executed eagerly while Observables are executed lazily. Let us see an example and understand the execution.

const testPromise = new Promise((resolve) => {
	console.log(“Execution of callback”);
	resolve(true);
});
testPromise.then(() => {
	console.log(“Promise Resolved);
})
console.log(“Exit”);

So the console output for this will be:

Execution of callback

Promise Resolved

Exit

const testObservsable = Observable.create( observer => {
 	console.log(“Execution of Observable”);
observer.next( '1' )
 	observer.complete()
   })
 
console.log(“Before subscribe”);
 
testObservable
      .subscribe(() => console.log(“Execution of subscribe”))
}

So the console output for this will be:

Before subscribe

Execution of Observable

Execution of subscribe

Here, “Execution of Observable” will be only printed to the console after we subscribe to it.

Conclusion

So now we know what are the differences between an observable and a promise. We can decide accordingly what is to be used and when. Both are great options for solving the aysnc paradigm but it depends on your use case. You can learn more about Observable here.

For more updates, please follow our LinkedIn page- FrontEnd Studio.

Thank you for sticking to the end. If you like the blog, please don’t forget to give a thumbs up and share it. Feel free to share your thoughts about this blog in the comments.

Written by 

Kiran Jeet Kaur is working as a Software Consultant in Knoldus. Her practice area is Front End. She is always open to learn new things. Her hobbies include watching movies and listening to music.