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)
The solution does not explain the reason.
imho the problem would be solved if you replace
with
There seems to be a misconfiguration in your typescript.
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?