Angular - Difference between Observable and Promise

3

I understand that an Observable is a promise but with filters to be able to make asynchronous calls without having to make many requests.

I think I understand the concept but I do not have it clear in practice.

In addition to a word search that other examples would use an Observable and in which others a Promise?

    
asked by Archagy 01.06.2017 в 06:23
source

2 answers

5

Promise

A Promise handles a single event when an asynchronous operation completes or fails.

There are Promise libraries out there that allow cancellation, but ES6 Promise has not done so far. At least not that I have found yet.

Observable

A Observable is a data flow ( Stream in other languages) and allows to pass zero or more events where a callback is invoked for each event.

Often Observable is preferred before Promise because it provides the characteristics of Promise and much more. With Observable it does not matter if you want to handle 0, 1 or several events. You can use the same API in each case.

Observable also has the advantage over Promise that can be canceled. If the result of an HTTP request to a server or some other expensive asynchronous operation is no longer necessary, the Suscription of a Observable allows canceling the subscription, while a Promise will eventually call the success or rejection callback, Even if you do not need it anymore.

Observable provides operators such as map (), forEach (), reduce (), ... similar to an array

There are also powerful operators like retry (), or replay (), which are often very useful.

In my case, when I started using Observable , I completely forgot about Promise .

I hope the explanation is clear, otherwise, do not hesitate to ask everything you need.

    
answered by 01.06.2017 / 16:46
source
-1

I leave you a very interesting article about what it is, and how the observable is used. I hope it helps you:)

Observables

    
answered by 01.06.2017 в 12:13