Should we unsubscribe from ngxs Selector?
Asked Answered
B

3

14

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));
Benthos answered 11/6, 2019 at 8:7 Comment(1)
Yes you should. This is one of the ways you can unsubscribe: alligator.io/angular/takeuntil-rxjs-unsubscribeWhipstitch
S
20

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.

Squally answered 11/6, 2019 at 11:33 Comment(1)
I agree with Scuba Kay. It's exactly what we do in our enterprise project.Postorbital
P
3

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 :)

Princess answered 11/6, 2019 at 11:40 Comment(0)
G
2

Yes, if you subscribe manually in the component then you need to unsubscribe.

Best to avoid that if possible and subscribe in the component template using the async pipe.

Gianina answered 11/6, 2019 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.