DEV Community

Rich Field
Rich Field

Posted on

3 1

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! 🙄

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay