Skip to content Skip to sidebar Skip to footer

Observer Subscribe Not Firing On First Load To Component

I have a store which exposes an asObservable. A view subscribes to this and displays the data. It was working on first load since I've changed it to a Singleton service, when I fir

Solution 1:

Sequence of events is as follows (confirmed during debugging):

  1. Data is loaded from server
  2. subject.next() is called with correct data
  3. component constructor is called which subscribes to observer

It's because the vanilla Subject doesn't buffer anything. When a message is emitted, if there is no one subscribed at that exact time, then the message is gone forever and no one will receive it.

If you want to keep the last message buffered (for all subscribers), then you can use the BehaviorSubject or the ReplaySubject

import { BehaviorSubject } from'rxjs/BehaviorSubject';
import { ReplaySubject } from'rxjs/ReplaySubject';

sub1 = newBahaviorSubject<any>(null);
sub2 = newReplaySubject<any>(1);

Semantically, the BehaviorSubject represents a value that changes over time, and you initialize it with the initial value. It will keep the last item always buffered until the next item pushes it out.

The Semantics of the ReplaySubject is to buffer the number of items emitted, up to the buffer size, and send them all to subscribers when subscribed to. We can initialize the ReplaySubject with a buffer size. A buffer size of 1, will make it behave just like a BehaviorSubject (but we don't need to initialize it with a value).

Post a Comment for "Observer Subscribe Not Firing On First Load To Component"