Utilizing a service called "settings", initial persisted values are read and provided through an observable named "settings$" to components that subscribe to it. Many components rely on this observable to retrieve the initial values and exchange updated values among themselves using BehaviorSubject implemented in the service.
@Injectable()
export class SettingsService implements OnInit {
settingsBS;
settings$: Observable<SettingsI>;
init() {
this.settingsBS = new BehaviorSubject<SettingsI>(defaultSettings);
this.settings$ = this.settingsBS.asObservable();
...
let s: SettingsI;
this.loadPersistedSettings(s);
// notify subscribers about the
// loaded persisted settings
// and pass these settings to them
this.notifySubscribers(s);
...
}
// this function is also used by components
// to pass new/updated settings to subscribers
public notifySubscribers(s: SettingsI) {
this.settingsBS.next(s);
}
...
}
While most functionality works as expected, one particular component requires access to the initial persisted data but does not wish to receive further updates for "settings". Thus, the component subscribes initially to obtain the data and then unsubscribes to prevent any future updates as demonstrated below.
constructor(private settingsService: SettingsService, ...) { ... }
ngOnInit() {
const settingsSubscription = this.settingsService.settings$.subscribe(o =>
{
merge(this.persistedSettings, o);
...
});
...
settingsSubscription.unsubscribe;
}
Despite calling "settingsSubscription.unsubscribe;", the subscription persists and the section inside the subscription continues to trigger whenever the service function:
settingsService.notifySubscribers(s)
This raises two questions:
Why does "settingsSubscription.unsubscribe;" fail to cancel the subscription?
How can this issue be resolved?