What does subscribe do, and how it is related to O

2019-02-16 06:49发布

问题:

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, and why do we always have to call observable.subscribe()?

What does subscribe() actually do?

回答1:

What is an 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.

Hot vs. Cold Observable

There are two kind of Observables: cold and hot ones.

  • Cold Observables: Those are Observables that do not emit data until you subscribe to them, basically, data does not exists until you ask for it (e.g. Ajax requests).
  • Hot Observables : These ones start emitting without caring if there is or not a subscriber waiting for data.

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:

  • A cold Observable is like a VOD service : Videos are broadcasted when you ask for it (subscribe()).
  • A hot Observable is like regular TV : Video are broadcasted without any regard to the fact that anyone asks for it or not.

ConnectableObservable: warming cold Observables

What? ConnectableObservable? You said there was only two kind of Observable. You're a liar!

Not really; ConnectableObservables are Observables 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()).



回答2:

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.