9

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?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Mohit Harshan
  • 1,916
  • 1
  • 18
  • 41

2 Answers2

8

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

djolf
  • 1,196
  • 6
  • 18
  • 1
    This is the correct answer. When using rxjs, its very important to know the difference between Subject, BehaviorSubject and ReplaySubject (ReplaySubject isnt used that much, usually you will use Subject or BehaviorSubject). – Davy May 15 '19 at 13:11
0

Do it this way:

private currnetRightsSubject: BehaviorSubject<string[]>;
public currentRights: Observable<string[]>;

constructor() {
    this.currnetRightsSubject= new BehaviorSubject<string[]>(/*.......*/);
    this.currentRights= this.currnetRightsSubject.asObservable();
}

public get currentRightsValue(){
    return this.currnetRightsSubject.value;
}

updated

fill the BehaviorSubject like this:

this.currnetRightsSubject.next(someValue);
Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33