Search code examples
angularngxs

Should we unsubscribe from ngxs Selector?


I'm using ngxs State management. Do I need to unsubscribe from Selectors or is this handled by ngxs?

@Select(list)list$!: Observable<any>;

this.list$.subscribe((data) => console.log(data));

Solution

  • For the first example you can use in combination with the Async pipe. The Async pipe will unsubscribe for you:

    In your ts file:

    @Select(list) list: Observable<any>;
    

    In your html file:

    <ng-container *ngFor="let item of list | async">
    </ng-container>
    <!-- this will unsub automatically -->
    

    However, when you want to use the actual subscribe method, you will need to unsubscribe manually. Best way to do that is using takeUntil:

    import {Subject} from 'rxjs';
    import {takeUntil} from 'rxjs/operators';
    
    @Component({
      selector: 'app-some-component',
      templateUrl: './toolbar.component.html',
      styleUrls: ['./toolbar.component.scss']
    })
    export class SomeComponent implements OnInit, OnDestroy {
      private destroy: Subject<boolean> = new Subject<boolean>();
    
      constructor(private store: Store) {}
    
      public ngOnInit(): void {
        this.store.select(SomeState).pipe(takeUntil(this.destroy)).subscribe(value => {
          this.someValue = value;
        });
      }
    
      public ngOnDestroy(): void {
        this.destroy.next(true);
        this.destroy.unsubscribe();
      }
    }
    

    You can use pipe(takeUntil(this.destroy)) for every subscription in your component without the need to manually add unsubscribe() for every one of them.