Search code examples
angularrxjsbehaviorsubject

Rxjs: BehaviourSubject value emission


I have a behaviour subject BehaviorSubject<MyModel>(new MyModel). As per the readings done by me, I learned that whenever a subscription is done to behaviour subject, the subscriber gets a default MyModel object as soon as the subscription is done.

But I am confused on this scenario, suppose some ClassA subscribed on the behaviour subject and then emitted a value on the obsevrable after tweaking with it. After the ClassA has emitted, ClassB subscribes on the subject, so now does ClassB on subscription receives the new MyModel() object or the model last emitted by the subject.

Please let me know if further clarification is required.


Solution

  • This started as a comment but turned into an answer:

    In your scenario, the ClassB instance will get the MyModel instance emitted by your ClassA instance, not the one you created initially via new MyModel().

    In general, BehaviorSubject immediately fires the single most recently-emitted value on new subscriptions - this behavior is what defines a BehaviorSubject - versus, for instance, a ReplaySubject immediately emits all values that have been emitted so far on each new subscription.

    Note this is easy to demonstrate empirically: