Unsubscribing from Observables in Angular

Why is this important?

ngOnInit() {
this.observable.subscribe((value) => {
// important logic on app state, modification of DOM, etc.
});
}

unsubscribe()

this.someObservable = interval(1000).subscribe((value) => {
console.log('value: ', value);
});
ngOnDestroy() {
this.someObservable.unsubscribe();
}

take(n)

this.someObservable = interval(1000).pipe(take(5))
.subscribe((value) => {
console.log('value: ', value);
});

takeUntil(x)

private unsubscribe: Subject<any> = new Subject<any>();
interval(500).pipe(takeUntil(this.unsubscribe))
.subscribe((value) => {
console.log('observable 1: ', value);
});
interval(1000).pipe(takeUntil(this.unsubscribe))
.subscribe((value) => {
console.log('observable 2: ', value);
});
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}

Final Thoughts

--

--

--

Full-stack software engineer specializing in web and mobile development. Always learning new things. “There is no growth in the comfort zone…”

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Day 46 | 100 Days Full-Stack Challenge

React Form Handling with useReactiveForm

A quick and dirty Continuous Delivery for a NestJs Application on DigitalOcean with Gitlab CD

Solution for Maximo BIRT Report Exception of “MXReportScriptContext” is not defined.

How to run ESLint using a pre-commit hook

The Principle of Least Power

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jacob Neterer

Jacob Neterer

Full-stack software engineer specializing in web and mobile development. Always learning new things. “There is no growth in the comfort zone…”

More from Medium

Angular Best Practices: Foundation For Performant Angular Apps

[Rxjs] Rxjs store for angular (rx-ng-store)2

Angular 12 @Input And @Output

Update Angular 10 to 13