0

In this article a the merge operator is being used to subscribe to both sort and paging events. The function looks like this:

    merge(this.sort.sortChange, this.paginator.page)
        .pipe(
            tap(() => this.loadLessonsPage())
        )
        .subscribe();

Do we need to hold on on to the subscription and call unsubscribe when the component is destroyed?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

1

Short answer: Yes!

More expanded answer: You don't have to do it manually!

You can use plenty of operators to help you manage the subscription. An even better way to not manage the subscription at all is to let your HTML do it for you using the AsyncPipe.

Example:

component

this.sortAndPaging = merge(this.sort.sortChange, this.paginator.page)
        .pipe(
            tap(() => this.loadLessonsPage())
        )
html

<div *ngIf="sortAndPaging | async as sortAndPaginaData">
 {{ sortAndPagingData | json }}
</div>

This way, Angular's lifecycle management in combination with the AsyncPipe will keep track and subscribe/unsubscribe from the subscription itself.

Another powerful solution, as I mentioned earlier, is using operators to do it. RxJS comes with plenty of powerful tools like first(), take(x), takeUntil() and takeWhile() that will complete and unsubscribe automatically for you.

take(10) will complete and unsubscribe after 10 values have passed through for example.

More specific tips for your situation will require a more expansive question and some examples of what you've tried.

Bjorn 'Bjeaurn' S
  • 3,861
  • 2
  • 18
  • 29