DEV Community

Rich Field
Rich Field

Posted on

Initialise BehavorSubject correctly

For some reason a BehaviorSubject I was calling next on was not firing events. It only fired with the initial value.

This was my declaration.

private clients: BehaviorSubject<ClientSummary[]> = new BehaviorSubject(undefined);
public clients$: Observable<ClientSummary[]> = this.clients.asObservable();

And how it was being consumed.

this.clientService.clients$.subscribe(clients => {
  // do something with clients  
  console.log(clients);
});

When the page loaded, the observable fired with the following log.

undefined

However, when next was called on the BehaviorSubject, the observable did not fire again.

this.clients.next([/* some clients*/]);

Can you see the problem?

It's very subtle and took me a while to track down.

Solution

Update the initial value!

private clients: BehaviorSubject<ClientSummary[]> = new BehaviorSubject([]);

I don't know why the initial value is significant; but with this change the observable now updates each time next is called on the BehaviorSubject.

As for why I had undefined in there in the first place?
Probably copy and paste! 🙄

Top comments (2)

Collapse
 
moncapitaine profile image
Michael Vogt

The solution does not explain the reason.

imho the problem would be solved if you replace

private clients: BehaviorSubject<ClientSummary[]> = new BehaviorSubject(undefined);

Enter fullscreen mode Exit fullscreen mode

with

private clients: BehaviorSubject<ClientSummary[] | undefined> = new BehaviorSubject(undefined);

Enter fullscreen mode Exit fullscreen mode

There seems to be a misconfiguration in your typescript.

Collapse
 
kildareflare profile image
Rich Field

Hey @nyagarcia , you seem to know your RxJS pretty well.
Do you know why the initial value for the BehaviorSubject is important?
I.e. why it's important it starts as an array and not undefined?