Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BehaviorSubject firing twice

Tags:

rxjs

angular7

Im using BehaviourSubject from RxJS:

private rights = new BehaviorSubject<Array<string>>([]);


updateRights(rights: Array<string>) {
  this.rights.next(rights);
}

getRights(): Observable<any> {
  return this.rights.asObservable();
}

I'm updating the rights in the root component and im subscribing to it in another component like:

 this.configService.getRights().subscribe(res => {
   console.log(res);
 })

This subscription is firing twice. Once when the data is empty and then again when the data is received.

I want the subscription to fire only once and get only the latest data. What should be done?

like image 760
Mohit Harshan Avatar asked May 15 '19 08:05

Mohit Harshan


1 Answers

BehaviourSubject emits the value on subscription by default, and it is intended design. If you do not want this behaviour, use Subject instead.

like image 75
djolf Avatar answered Sep 25 '22 15:09

djolf