What could be causing the increasing memory usage in my web application every time a server request is made?

My real-time app constantly calls a function to retrieve the latest data:

getInformation() {
    this.dateService.getDates().subscribe((data: Appointment[]) => {
      this.totalDates = data;
    });
    this.presentationService.getPresentations().subscribe((data: Presentation[]) => {
      this.totalPresentations = data;
    });
    this.roomService.getBookings().subscribe((data: Booking[]) => {
      this.totalBookings = data;
    })
  }

However, with each call, the RAM usage in the task manager increases by 0-1 MB. While this has not been an issue on my Windows PC, I am concerned about running this web-app on a Raspberry Pi kiosk system. The specific model I'm using only has 926 MB of RAM, and after approximately 20 minutes, it maxes out causing the system to freeze.

I attempted reducing the frequency of calling the function (e.g., every 3 seconds), but this only resulted in a more rapid decrease in available RAM.

Answer №1

each passing second prompts a call to this function

This situation presents a problem. It appears that each call initiates an HTTP request (presumably to the same domain). Most browsers have a limit on the maximum number of simultaneous connections to a domain (such as Chrome with a limit of 6). One possible solution is to utilize RxJS, specifically using forkJoin and unsubscribe from previous requests to cancel any pending requests before making another one. Consider implementing the following:

import { forkJoin } from 'rxjs';

class SomeComponent implements OnInit, OnDestroy {
  infoSubscription: any;

  getInformation() {
    if (this.infoSubscription) {
      this.infoSubscription.unsubscribe();
    }

    this.infoSubscription = forkJoin({
        dates: this.dateService.getDates(),
        presentations: this.presentationService.getPresentations(),
        bookings: this.roomService.getBookings()
      }
    )
    .subscribe(
      response => {
        this.totalDates = response.dates;
        this.totalPresentations = response.presentations;
        this.totalBookings = response.bookings;
      }
    );
  }

  ngOnDestroy() {
    if (this.infoSubscription) {
      this.infoSubscription.unsubscribe();
    }
  }
}

While this approach still involves manual triggering of a request every second, there is a risk of losing information if the backend takes longer than a second to respond. A better solution in this scenario would be to implement Server-Sent Events.

Answer №2

The reason could be the frequent subscription call triggers!

Answer №3

It seems like you are utilizing the setInterval method, which may lead to a buildup of stack frames on the heap. The multiple subscriptions you have should not impact memory significantly, as long as the Observable completes properly. To optimize your code in a more rxjs fashion, consider the following approach:

By restructuring your call as shown below, you only need to invoke getInformation() once:

getInformation() {
  interval(1000, animationFrameScheduler).pipe(
    switchMap(() => forkJoin({
      dates: this.dateService.getDates(),
      presentations: this.presentationService.getPresentations(),
      bookings: this.roomService.getBookings()
    }))
  ).subscribe(({ dates, presentations, bookings }) => {
    this.totalDates = dates;
    this.totalPresentations = presentations;
    this.totalBookings = bookings;
  });
}

You can experiment with different schedulers such as the animationFrameScheduler instead of the default asyncScheduler, which may reduce the number of stack frames generated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to bind input data with interface in Ionic 4 – issues persist

I am working with an interface in Ionic that looks like this: // mydata.model.ts export interface Mydata{ id: string; name: string; date: string } To add new data to the backend, I am binding my data within my component using <ion-input> a ...

Is it possible to use programming to invoke a function with the identical name from within another function in Javascript or Typescript?

Currently, I am working with Typescript but presenting this question in Javascript. Any assistance for either language would be greatly appreciated. I have two objects that share the same interface. My goal is to create a third object with the same interf ...

I'm looking to convert this typescript function to return an array with strong typing instead of just a plain string[]

I am currently in the process of converting a JavaScript function to TypeScript. Originally, I believed that the type of the variable hi would be ('s'|'bb')[], but it turned out to be string[]. Is there a way for TypeScript to automatic ...

The configuration file for Typescript and Typeorm, specifically the .ts file, is encountering an error

Hello, I'm encountering an issue with my app.ts. When trying to load my settings from ormconfig.ts for the typeorm function that creates the connection, I receive the following error: No overload matches this call. Overload 1 of 3, '(name: stri ...

How to retrieve query parameters using Angular 2's HTTP GET method

Seeking assistance on my Ionic 2 app built with Angular 2 and TypeScript. I am familiar with older versions of Angular, but still adjusting to this new environment. I have set up my API with basic query strings (e.g domain.com?state=ca&city=somename) ...

Guide for using two Async Pipe functions in Angular 7

Two different functions are in place to check a specific condition, and the requirement is for both of them to be true simultaneously. How can *ngIf be utilized to achieve this? Currently, setting just one of them works, but the aim is to have both. HTML ...

Respond to unsuccessful changes within a simple presentational element

Within my component, I have a feature that allows users to interact with and modify a specific entity. However, these modifications may be rejected at the server level. In such cases, I would like the component to initiate an animation to indicate to the u ...

How do I access the main outlet route in Angular 8 while being in a different router outlet?

Hey there, I'm a newcomer to Angular and still trying to grasp the concept of router outlet. {path: 'organisation/:orga_id/event/:event_id', component: EventAdminComponent, children: [ {path: 'general', component: ...

Display a second dialog to the left of the first dialog at the same level using Angular Material

Scenario: I have a customer record and would like to show additional read-only information in a separate dialog. This requires some selections. In Angular Material, I already have one modal dialog open and find it relatively easy to open a second one. Che ...

Creating a custom function in TypeScript to redefine the functionality of the `in` operator

I am looking to create a custom function that mimics the behavior of the in operator in TypeScript, utilizing user-defined type guards. (To see an example, check out Lodash's has function.) When using n in x where n is a string literal or string l ...

Service consumption across various components is failing to function as intended

I'm working on implementing a side navigation bar and content div. The goal is to display the innerText of the selected navigation item in the content div whenever an element in the side nav is clicked. Below is my current code setup: sidenav.compone ...

Restoring scroll position in Next.js when the page is reloaded

Problem Description I am facing an issue with the sticky header functionality I have implemented. It relies on a useEffect hook to monitor its scroll Y offset state. However, when I reload the page, it fails to detect the position until I manually scroll ...

When using NodeJS and TypeScript, the URL query function may encounter issues when multiple parameters are included

This is the code snippet for a controller in my route: export const getHotels = async ( req: Request, res: Response, next: NextFunction ) => { try { const hotels = await Hotel.find(req.query).limit(+req.query.limit); res.status(200).json ...

Angular: Implementing a dialog in a component with an established constructor

Within my current component, I have implemented a constructor that injects TestService. However, I now need to add a button that will open a popup dialog. How can I achieve this without interfering with the existing constructor? Thank you for your help. ...

"Capture the selected option from a dropdown menu and display it on the console: A step-by-step

Is there a way to store the selected value from a dropdown in a variable and then display it on the console? HTML <select class="form-control box" id="title" required> <option *ngIf="nationality_flag">{{nationality}}</option> &l ...

Angular version 4 JSONP request callback

Currently, I am working on the migration of an Angular 1 application to Angular 4. One particular challenge I have encountered is a jsonp call to an endpoint over which I have no control. In the Angular 1 app, the following code snippet is being used: js ...

Trouble with Angular not Displaying BootStrap 5.0 Styles

Trying to implement both BootStrap and Angular into the project, I successfully applied the styles by adding the following line in the index file: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="sty ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

Employing [style.something.px]="2" in Angular to specify the thickness of the border

Presently, I am setting the width of the element using this code format: <div [style.width.px]="size" [style.height.px]="size"></div> What I am aiming for is to utilize a comparable format but to define the border-width css attribute, such as ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...