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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

So is it automatically done somehow?
This should be a comment, mate :)
But I thought at a minimum we would need something like that and to implement OnDestroy?
I would advise using the takeUntil approach (if you can't use the async pipe), and having a Subject which only emits in ngOnDestroy. This saves you from having a thousand subscription variables: ngOnDestroy() { this.destroy$.next(true); }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.