loading...

Initialise BehavorSubject correctly

kildareflare profile image Rich Field ・1 min read

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

Posted on Mar 28 by:

kildareflare profile

Rich Field

@kildareflare

Full stack remote dev that prefers the front end. I build web applications for NPOs and businesses large and small.

Discussion

markdown guide
 

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?