Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise vs Observable for Http in Angular2? [duplicate]

Essentially, what the title says, is there any reason to use an observable over a promise for the purposes of making http calls? Seems like needless overcomplication, since all the call will do is succeed or fail, and there is no real reason to cancel it, virtually ever. Asking this for the typical use-case, not for the typical observables sales-pitch of debounce (which, ironically, ng-debounce does just fine anyway, without making useless calls).

like image 865
VSO Avatar asked Nov 02 '16 13:11

VSO


People also ask

Which is better observables or promises?

the Promise is always asynchronous, while the Observable can be either asynchronous or synchronous, the Promise can provide a single value, whereas the Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to the Observable to get a new tailored stream.

What are the advantages of Observable over Promise?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.

What is difference between Promise and observables?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time.

When should you use observables?

An Observable is ideal for situations where the data changes during its lifetime. Real-time data from a WebSocket, for example. Think about dashboards, chat messages, notifications, video subtitles, sound visualizations.


2 Answers

There is a huge advantage of observables that is quite relevant here.

Observable supports cancellation while Promise doesn't.

Using subscribe() and map(), instead of then() doesn't seem to add much complication to me. You can also use toPromise() to get a Promise if that is what you need.

See also Angular - Promise vs Observable for more details.

Also if FRP style of programming is used it's handy to get an observable everywhere. If that is not desired just using toPromise() gives a Promise and the slightly simpler API.

like image 137
Günter Zöchbauer Avatar answered Oct 11 '22 18:10

Günter Zöchbauer


The very basic difference between promise and observable is Observable module will not work if no functionality subscribed to it. Hence less burden to your server.

Where as in promise, whether you are truly utilising the response or not, it will send you a promise object after pinging your server with your request and payload; Which sometime undesirable.

The funda is to decrease the load of node or other server.

like image 38
Jyotirmay Avatar answered Oct 11 '22 19:10

Jyotirmay