BehaviorSubject vs PublishSubject

后端 未结 4 1354
北海茫月
北海茫月 2021-02-05 01:29

I\'m trying to get my head around the golden rule (if any) about:

When to use BehaviorSubject ?

and

When to

4条回答
  •  情深已故
    2021-02-05 02:08

    PublishSubject: Starts empty and only emits new elements to subscribers. There is a possibility that one or more items may be lost between the time the Subject is created and the observer subscribes to it because PublishSubject starts emitting elements immediately upon creation.

    BehaviorSubject: It needs an initial value and replays it or the latest element to new subscribers. As BehaviorSubject always emits the latest element, you can’t create one without giving a default initial value. BehaviorSubject is helpful for depicting "values over time". For example, an event stream of birthdays is a Subject, but the stream of a person's age would be a BehaviorSubject.

提交回复
热议问题