angularrxjsrxjs-observables

Is unsubscribing handled automatically for Angular/RxJS Observables


I have heard that Angular automatically handles unsubscription for it's own Observables and therefore there is no need for manual unsubscription from an observable.

I was left with the impression that I should unsubscribe from an Observable if it is a custom one. I am looking for an explanation on this and where am I mistaken.

Example:

constructor(
        private _route: ActivatedRoute) {
            this._route.queryParams.subscribe(params => {
                if (params.id) {
                    this.show(params.id);
                }
            });
    }

vs.

constructor(
        private _route: ActivatedRoute) {
            this._route.queryParams.pipe(takeUntil(this._unsubscribeAll)).subscribe(params => {
                if (params.id) {
                    this.show(params.id);
                }
            });
    }

I am using ActivatedRoute's queryParams observable and I was left with the impression that here Angular automatically handles the unsubscription and I don't have to do it manually.


Solution

  • If you do a manual subscribe like in your examples you should also do an unsubscribe. The takeUntil idiom you showed where _unsubscribeAll is completed in the teardown is very common.

    Angular does automatic unsubscriptions when using async pipes, so if you render an Observable in your html template with something like myObs | async you do not need this.