v19 launch sale ends in ... Get 25% off BUY NOW
3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 7

Handling Manual Subscriptions

STANDARD

Handling Manual Subscriptions

Sometimes we might find ourselves in situations where we need to manually subscribe to an observable stream. This might be true when the “destination” for your data isn’t actually the template. Maybe you want to send a POST request to send data to a server, and don’t need to display anything about that request in the template. Maybe you have some kind of logging service that sends analytics to some remote backend — the data is just leaving your application so, again, maybe you want to perform a manual subscription to send that data on its way.

As you will soon see, even the Signals and RxJS state management approach we will be using for the applications we will be building — the state management approach that is designed around being as reactive/declarative as practical — explicitly uses manual subscriptions to observable streams sometimes.

Manual subscriptions are best avoided, but sometimes they are simply necessary or perhaps just convenient.

How to Unsubscribe Manually

If you do subscribe manually at some point, it is important to understand how to unsubscribe safely. If you ever write .subscribe() in your code you should always make sure you unsubscribe from that stream at some point.

Technically, there are situations where you don’t have to unsubscribe — certain types of observables might just emit one value and then complete. If the complete() notifier has been called, then the stream is already unsubscribed so there would be no need to do it manually.

This is a dangerous game to play, even in situations where it seems like it might be safe to not bother with unsubscribing there might be tricky little gotchas you aren’t considering.

For example, a lot of people will say that if you subscribe to a http.get() request in Angular you don’t need to worry about unsubscribing because it just emits on value and then completes. The second part of that statement is true enough, but not unsubscribing may still cause unintended consequences.

You might have some code like this:

this.http.get('someapi').subscribe((val) => {
  // do something within the currently active component
})

But what if the user leaves the page before the HTTP request finishes? If your subscriptions aren’t unsubscribed when the component is destroyed then you could have side effects of your HTTP request being triggered when the component doesn’t even exist anymore. This may or may not cause problems.

Rather than trying to reason about when you need to unsubscribe and when you don’t, it is much safer to always apply the general rule of: always unsubscribe.

I am going to show you a few different ways to handle unsubscribes that you might come across in codebases — there have been many different ways people have approached this over the years.

But, there is a new way in Angular to handle unsubscribing: the takeUntilDestroyed operator. This is almost always going to be the preferable option and it is what we will be relying on in this course.

Let’s start with the more “manual” approach first to see what exactly it is we are trying to do, and then we will cover takeUntilDestroyed and some more options. We will also look at some other ways of unsubscribing that may still be useful in certain circumstances, or you might just come across these methods in older codebases.

Store a reference to the subscription

This is the sort of “obvious” way to unsubscribe but I generally wouldn’t recommend doing this as other ways are generally more efficient. Still, I think it is important to cover since it sort of the default way to go about it.

export class HomeComponent implements OnInit, OnDestroy {

    emitOnceASecondSubscription: Subscription;

    ngOnInit(){
        const emitOnceASecond$ = interval(1000);
        this.emitOnceASecondSubscription = emitOnceASecond$.subscribe((val) => console.log(val));
    }

    ngOnDestroy(){
        this.emitOnceASecondSubscription.unsubscribe();
    }
}
STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).