Promise emits a single value while Observable emits multiple values. So, while handling a HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.
Let’s implement this with an example.
Promise
const promise = new Promise((data) =>
{ data(1);
data(2);
data(3); })
.then(element => console.log(‘Promise ‘ + element));
Output
Promise 1
Observable
const observable = new Observable((data) => {
data.next(1);
data.next(2);
data.next(3);
}).subscribe(element => console.log('Observable ' + element));
Output
Observable 1
Observable 2
Observable 3
So, in the above code snippet, I have created promise and observable of Promise and Observable type respectively. But, promise returns the very first value and ignore the remaining values whereas Observable return all the value and print 1, 2, 3 in the console.
Promise is not lazy while Observable is lazy. Observable is lazy in nature and do not return any value until we subscribe.
product.component.ts (Observable)
getMenu() {
this.productService.getFoodItem();
}
}
In above example we are not subscribing the observable, so we do not receive the data and even there would be a no network call for this service.
product.component.ts (Observable)
getMenu() {
this.productService.getFoodItem().subscribe((data => {
this.foodItem = data;
}),
error => console.log(error));
}
}
Here, we have subscribed our Observable, so it will simply return the data. But Promise returns the value regardless of then() method.
product.component.ts (Promise)
getMenu() {
this.homeService.getFoodItem()
.then((data) => {
this.foodItem = data;
});
}
Observable is cancellable in nature by invoking unsubscribe() method, but Promise is not cancellable in nature.

Comments
Post a Comment