Should we unsubscribe from ngxs Selector?

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.


The Async Pipe solution is usually the best.

Depending on your use case, you can also use the first() operator.

observable.pipe(first()).subscribe(...)

It is shorter than the takeUntil approach and you don't need any unsubscribe.

https://www.learnrxjs.io/operators/filtering/first.html

Beware: This will return a value and unsubscribe. So it can be used if you need a current value from the store and then do something with it. Don't use it to display something on the GUI - it will only show the first change :)

Tags:

Angular

Ngxs