I\'m new to Angular and the tutorial I followed has the term \"Observable
\". The tutor explained it, but I didn\'t completely understand.
What is an
Observable is independant of Angular. It provide you a convenient way to handle async flow. And Angular use it.
So what you need to learn is how the Reactive Programming work. It's too complex to explain it in one response but you've got a lot of content about rxjs.
One of the first i read is this post The introduction to Reactive Programming you've been missing, i think it's a good introduction to Reactive Programming.
Observable
?An Observable can be seen as a data source. That data might exist (or not) and might change over time (or not).
An Observable emits data, until it has nothing to emit anymore and then completes (there are some Observable that will never complete) or throws an exception (error handling is a big part of Observable
combination).
You can combine these data-sources or alter the emitted data using operators like map
, merge
, switchMap
, etc. So, a data-source can be an alteration of another data-source or the combination of many others.
As I said, an Observable
is a source, If you want to use the data from that source, you need to subscribe()
to the Observable
and then you get notified of any data emitted.
Observable
There are two kind of Observables: cold and hot ones.
Most of the time, you have to deal with cold Observables (AJAX requests), that's why you need to subscribe to them, without this subscription you only define a data source, and then never trigger the request.
So let's think about Observable
with a video metaphor:
Observable
is like a VOD service : Videos are broadcasted when you ask for it (subscribe()
).Observable
is like regular TV : Video are broadcasted without any regard to the fact that anyone asks for it or not.ConnectableObservable
: warming cold Observable
sWhat? ConnectableObservable
? You said there was only two kind of Observable. You're a liar!
Not really; ConnectableObservable
s are Observable
s that emit data as soon as you call their connect()
method. In other words, this Observable becomes hot as soon as you call the connect()
method.
You can turn a cold Observable
into a ConnectableObservable
using some operators (like publish()
).