* ngxs: 3
* @angular/core: 6
I have used ngxs for some time. There is a tip on angular world: dont forget to unsubscribe. With ngxs we use subscription on the state class and components.
What tip and suggestion do you have on this subject? Do I also need to unsubscribe the subscriptions that are in the ngxs class?
Nope. Its handled for you.,
Hey @amcdnl can you confirm that when using the @Select decorator in a component, you do not need to unsubscribe on ngOnDestroy()? There's a bit of ambiguity with the original question. thanks!
@ejbeaty If you subscribe to the observable then you need to make sure that you unsubscribe.
The best way is probably using the takeUntil mechanism that many people are using. eg:
https://medium.com/thecodecampus-knowledge/the-easiest-way-to-unsubscribe-from-observables-in-angular-5abde80a5ae3
https://blog.angularindepth.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
PS. If you use the async pipe then the unsubscription of that particular usage will be handled for you.
Hi @markwhitfeld I have this code below. Do i need to unsubscribe? Thanks
this.route.queryParamMap
.pipe(map(params => params.get('page')))
.subscribe((page: any) => {
this.page = page;
console.log(page);
});
@markwhitfeld
We use ngxs in our app like this:
Component:
@Select(CreateCertificateState.step) public step$: Observable<string>;
Template:
<li role="presentation" *ngFor="let item of steps$ | async"
[ngClass]="{'active': item === (step$ | async), 'inactive': item !== (step$ | async)}">
...
</li>
There is no other subscription to the step$ observable except the async pipes. To check for leaks I used the heap snapshots of chrome. When I switch out of the component and the component is destroyed I can still find the observable of step$ in the dump. I tried to use the GC of chrome manually but after that the observable is still there. When I switch back into the component and destroy it again and take another heap dump, two observables with different IDs appear in the dump.
Could this be a problem with the chrome heap snapshot and the GC, or does it have to do with the selector?
@schnebdreleg
No, that's not a problem with chrome. The step$ will be released only when the component instance will be released. Angular doesn't release component instance (only invokes ngOnDestroy if it's declared). Its instance will be released later on some random mark&sweep cycle, not immediately.
@amcdnl
I was wondering the same and as I didn't find clear answer I added a question on StackOverflow
could you check the answers and advice if unsubscribe from ngsx state selector is required or not?
https://stackoverflow.com/questions/56539163/should-we-unsubscribe-from-ngxs-selector
Most helpful comment
Nope. Its handled for you.,