I am a newbie to Angular 2 and just came across a thing called Observables. It looks very similar to Promises. Could someone please explain me how it works internally and what are the pros of Observables?
They're actually two completely different things.
Promises help us with asynchronicity (is that a word?) in Javascript. They are a way to say: "Hey, I'll tell you when this function completes, and if it doesn't I can throw an error". This is helpful because unlike in other languages, javascript statements can execute all at the same time, without waiting on the other to finish first.
For example:
var a;
addFiveToA();
addTenToA();
So when your computer reads this, it'll call addFiveToA() and before that function finishes it'll have already called addTenToA(). Promises can help us fight this by allowing the function to tell us when it has finished. Note: you have to define your function to return a promise in order to use it (a helpful link to defining promises can be found below).
Example:
var a;
addFiveToA().then(function() {
// everything in here will be executed once addFiveToA() has finished executing
// Also defined as when the function 'resolves'
addTenToA();
}).catch(function(error) {
// if the promise 'rejects', this 'catch' will fire
});
This is a basic example, but when dealing with things like network requests, this is a big issue.
Read more on promises here
html5rocks.com/en/tutorials/es6/promises
Observables on the other hand, tell us when a piece of data has changed. So you can add an Observable to a variable, and it'll watch your variable for any changes that happen.
A good read on observables can be found here
In a find quick in google i arrive to this post i don't know so much about angular 2 because in my company still using angular 1.3, but i think can be interesting!
Sébastien Portebois
Software architect at Ubisoft
A very short (and imprecise) answer could be: a promise can be fulfilled once. But an Observable can emit multiple values. In short, it's like an asynchronous (think promise) event emitter.
This graph (you can find similar 4-quadrants graph in many ReactiveX articles) let you compare Promises and Observables:
Observables are really useful (compared to promises) when you have to deal with multiple values, keep - or not - the ordering, and takeUntil really shines. If you're already fluent with promises, have a quick read of The introduction to Reactive Programming you've been missing if a great way to get started with Observables.