I'm using a shareDataService using BehaviorSubject like below. My problem is that every time I call the service's next() method the listener subscription in any other component is called several times, looks like it received the same message several times. Is this expected behavior? How to prevent it?
The service is a singleton. I do not call changeMessage multiple times
@Injectable()
export class ShareDataService {
messageSource = new BehaviorSubject(someData);
currentMessage: Observable = this.messageSource.asObservable();
changeMessage(message) {
this.messageSource.next(message);
}
}
Subscription in component
ngDoCheck() {
this.shareDataService.currentMessage
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((message) => {
//Do stuff
}
});
}