How does the 'subscribe' and 'unsubscribe' work with Observable in Angular2?
My architecture is as following:
- CRUD(Repo) service that contains CRUD operations and returns an Observable
In-between service that talks to CRUD. This service is injected into components and contains private BehaviorSubjects. I expose the underlying values as such
get selectedClient(): Observable<Client> { return this._selectedClient.asObservable(); } get clients(): Observable<Client[]> { return this._clients.asObservable(); }At the component level, I access the data by subscribing to previously mentioned getters as such:
deleteClient() { this.selectedClient.subscribe(actualClient => { this.clientStore.deleteClient(actualClient).subscribe(response => { if (response) { this.router.navigate(['/clients']); } }); }).unsubscribe(); } updateClient() { this.clientUpdateForm.submitClientForm().subscribe(client => { if (client) { this.growlService.showInfoMessage("Client updated", client.firstName + " " + client.lastName); } }).unsubscribe(); } this.selectedClient.subscribe(client => { this.clientForm = this.clientUpdateForm.clientForm; }).unsubscribe();
First I want to ask, is there anything wrong with this design? Secondly, when do I need to unsubscribe and when not to?
The idea is that the selectedClient is the state object for the application.
However it brings all of this 'subscribe/unsubscribe' in every component, and from my understanding if you don't unsubscribe you will add another subscription to the subscription array, which means any change will now trigger the code under the subscription twice.
Should the app have the concept of 'selectedItem' at all?