Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the http service return observables instead of promises

Tags:

angular

I'm curious about the reasoning or discussion that lead to the angular 2 http service returning an observable instead of a promise for the response. I would understand the logic for something like a web socket connection or long-polling request, but the http service simply creates an XMLHttpRequest, and in the load event handler for the request, emits the response on the response observable and then completes the observable. Since this only returns one value, it seems to me like a promise would make more sense.

Edit: I am aware of the difference between observables and promises, and know that you can convert observables to promises and vice versa. My question is more about the reasoning behind the decision to return an observable instead of a promise.

like image 200
bringel Avatar asked Jan 11 '17 20:01

bringel


People also ask

Why are observables instead of promises?

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.

Why does Angular use observables instead of promises?

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.

Why Angular http return observable?

The Angular team has put in a lot of effort to support promises as a fallback for a lot of those features, but under the hood those promises are just converted to observables anyway. By making Http requests observables the Angular team is making async operations in the core consistent with everything elsewhere.

Can Promise convert to observable?

Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.


1 Answers

I think the main reason was that observables can be cancelled.

See also Angular - Promise vs Observable.

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

Günter Zöchbauer