BehaviorSubject vs Observable?

前端 未结 10 2521
迷失自我
迷失自我 2020-11-22 02:17

I\'m looking into Angular RxJs patterns and I don\'t understand the difference between a BehaviorSubject and an Observable.

From my underst

10条回答
  •  时光取名叫无心
    2020-11-22 02:57

    Observable and subject both are observable's means an observer can track them. but both of them have some unique characteristics. Further there are total 3 type of subjects each of them again have unique characteristics. lets try to to understand each of them.

    you can find the practical example here on stackblitz. (You need to check the console to see the actual output)

    Observables

    They are cold: Code gets executed when they have at least a single observer.

    Creates copy of data: Observable creates copy of data for each observer.

    Uni-directional: Observer can not assign value to observable(origin/master).

    Subject

    They are hot: code gets executed and value gets broadcast even if there is no observer.

    Shares data: Same data get shared between all observers.

    bi-directional: Observer can assign value to observable(origin/master).

    If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject

    ReplaySubject

    They are hot: code gets executed and value get broadcast even if there is no observer.

    Shares data: Same data get shared between all observers.

    bi-directional: Observer can assign value to observable(origin/master). plus

    Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

    In subject and replay subject you can not set the initial value to observable. So here comes Behavioral Subject

    BehaviorSubject

    They are hot: code gets executed and value get broadcast even if there is no observer.

    Shares data: Same data get shared between all observers.

    bi-directional: Observer can assign value to observable(origin/master). plus

    Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.

    You can set initial value: You can initialize the observable with default value.

提交回复
热议问题