

Why We Have To Unsubscribe An Observable In An Angular Application?
source link: https://www.learmoreseekmore.com/2021/11/why-we-have-to-unsubscribe-an-observable-in-angular-application.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Unsubscribe An Observable:
- Avoids Memory Leaks
- Aborting HTTP requests to avoid unwanted calls.
So in this demo, we will understand the case studies to unsubscribe an observable.
Memory Leaks:
- import { Injectable } from '@angular/core';
- import { BehaviorSubject } from 'rxjs';
- @Injectable({
- providedIn: 'root',
- export class TestService {
- randNumberSub: BehaviorSubject<number> = new BehaviorSubject<number>(
- Math.random()
- (Line: 8-10) Initialized 'BehaviorSubject' of type 'number'.
Now let's create components like 'sample1.component.ts' and 'sample2.component.ts' these will consume the 'test.service.ts' and listen for the 'BehaviorSubject' changes.
- import { Component, OnDestroy, OnInit } from '@angular/core';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- templateUrl: 'sample1.component.html',
- export class Sample1Component implements OnInit {
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.testService.randNumberSub.subscribe((data) => {
- console.log(`Sample1Component ==> RandomNumber: ${data}`);;
- (Line: 8) Injected our 'TestService'.
- (Line: 11-13) Listening for the 'BehaviorSubject' changes.
- import { Component, OnInit } from '@angular/core';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- templateUrl: 'sample2.component.html',
- export class Sample2Component implements OnInit {
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.testService.randNumberSub.subscribe((data) => {
- console.log(`Sample2Component ==> RandomNumber: ${data}`);
- buttonTest() {
- this.testService.randNumberSub.next(100);
- (Line: 8) Injected the 'TestService'.
- (Line: 11-13) Listening for the 'BehaviorSubject' changes.
- (Line: 16-18) The method that updates data to our 'BehaviorSubject', this method will be registered as a click event for the UI button.
- Run the application, 'Home' route configured to 'Sample1.component'. So in the browser console, we can check the 'BehaviourSubject' logs data to the console.
- Now navigate to 'Sample2.Component', since here also we listening for 'BehaviorSubject' we can see console log here is well
- In 'Sample2.Component', we have a button that can update the data to our 'BehaviorSubject'. So now we click the button we can observe subscription the 'Sample1.component' also executes in spite of we currently on the 'Sample2.component'. This is called observables memory leak happened due to no unsubscribing them.
Unsubscribe Observable To Resolve Memory Leak:
- import { Component, OnDestroy, OnInit } from '@angular/core';
- import { Subscription } from 'rxjs';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- templateUrl: 'sample1.component.html',
- export class Sample1Component implements OnInit, OnDestroy {
- sampl1sub?: Subscription;
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.sampl1sub = this.testService.randNumberSub.subscribe((data) => {
- console.log(`Sample1Component ==> RandomNumber: ${data}`);
- ngOnDestroy(): void {
- if (this.sampl1sub) {
- this.sampl1sub.unsubscribe();
- (Line: 9) Added a new 'Subscription' variable like 'sampl1sub'.
- (Line: 12) Assigning our 'BehaviorSubject' to the 'Subscription' variable.
- (Line: 16-20) finally calling 'unsubscribe' in the 'ngOnDestroy' method.
- import { Component, OnDestroy, OnInit } from '@angular/core';
- import { Subscription } from 'rxjs';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- templateUrl: 'sample2.component.html',
- export class Sample2Component implements OnInit, OnDestroy {
- sample2sub?: Subscription;
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.sample2sub = this.testService.randNumberSub.subscribe((data) => {
- console.log(`Sample2Component ==> RandomNumber: ${data}`);
- ngOnDestroy(): void {
- if (this.sample2sub) {
- this.sample2sub.unsubscribe();
- buttonTest() {
- this.testService.randNumberSub.next(100);
- (Line: 9) Added a new 'Subscription' variable like 'sample2sub'.
- (Line: 13) Assigning our 'BehaviorSubject' to the 'Subscription' variable.
- (Line: 17-21) finally calling 'unsubscribe' in the 'ngOnDestroy' method.
Now if we test again we can observe memory leaks won't appear again.
Abort HTTP Request To Avoid Unwanted calls:
- getAlbums() {
- return this.http.get("https://jsonplaceholder.typicode.com/albums");
- Add some API call logic in our 'test.service.ts'
- import { Component, OnInit } from '@angular/core';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- selector: 'apicall',
- templateUrl: 'apicall.component.html',
- export class ApiCallComponent implements OnInit {
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.testService.getAlbums().subscribe(data => {
- console.log(data);
- (Line: 11-13) Invoking the API call.
- import { Component, OnDestroy, OnInit } from '@angular/core';
- import { Subscription } from 'rxjs';
- import { TestService } from 'src/app/services/test.service';
- @Component({
- selector: 'apicall',
- templateUrl: 'apicall.component.html',
- export class ApiCallComponent implements OnInit, OnDestroy {
- apicallSub?:Subscription;
- constructor(private testService: TestService) {}
- ngOnInit(): void {
- this.apicallSub = this.testService.getAlbums().subscribe(data => {
- console.log(data);
- ngOnDestroy():void{
- if(this.apicallSub){
- this.apicallSub.unsubscribe();
- (Line: 10) Added a new 'Subscription' API like 'apicallsub'.
- (Line: 13) Assigning the HttpRequest observable to our 'apicallsub' variable.
- (Line: 17-21) Finally unsubscribing the HttpRequest in the 'ngOnDestroy' method.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Follow Me:
Recommend
-
35
It's turning out that 2019 is the year of the Observable store at ng-conf with several speakers advocating for this pattern in Angular apps. I recently hopped off a large project that used NgRx for state manageme...
-
41
As you all know, and many articles have talked abo...
-
37
A review of the different ways you can unsubscribe from Observables in Angular
-
37
RxJS & Angular — Unsubscribe Like a ProAll the patterns you will ever need to subscribe and unsubscribe from RxJS Observables in your Angular project!
-
9
Angular 8 Tutorial: Observable and RXJS Examples by Didin J., updated on Oct 13, 2019
-
8
The easiest way to unsubscribe from Observables in Angular ...is of course using the async pipe, b...
-
6
Reading Time: 2 minutesIn Angular, we can use either Promise or Observable for handling asynchronous data. Both get and post method of Http and HttpClient return Observable and it can be converted into Promise using toPromise() method. So, w...
-
8
在 Angular 專案中 RxJS 實現 Unsubscribe 取消訂閱的四種常見方法 RxJS 可以將所有 Observable 物件簡單區分成兩種不同類型的,一種是有限事件數量的 Observable 物件,例如 HttpClient 相關 API 在訂閱之後就只會有一筆資料回來,這...
-
6
Angular Observable vs Angular Promise: Differences, Uses & How To Build Them Desis...
-
6
(译)Angular架构03-如何使用`Observable`数据服务构建`Angular`应用程序及常见的设计缺陷 2018-10-17 约 3292 字 预计阅读 7 分钟...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK