What does subscribe do, and how it is related to Observable?

前端 未结 2 2024
礼貌的吻别
礼貌的吻别 2021-01-07 17:37

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

2条回答
  •  渐次进展
    2021-01-07 18:00

    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()).

提交回复
热议问题