How to clean up dynamically created class instances?

Viewed 55

just to preface-- I am new to angular so I apologize if this is not a good way to handle this problem!

So I have a scenario where there are x amount of rooms-- and for simplicity lets say that whenever someone goes in, I am able to get the time that happens.

So now I would like to see the elapsed time that someone has been in a room.

Here is the demo on Blitz.

I hardcoded the room instances but eventually I would fetch the values dynamically from a backend.

So the question I am trying to get to is if the way I am going about doing this process (specifically the elapsed time) the correct way? I set an interval in the RoomWidget Class and I manually set clear the interval with NgOnDestroy, but is that enough? I was thinking that even after doing that, the class instances are still alive and thus leaky. I just couldn't figure out a better way about solving this problem and felt as though I over complicated all of this.

I genuinely do appreciate any comments or constructive criticism I should be aware of for this stuff-- thank you!

1 Answers

I wouldn't bother managing the subscription myself. You can refactor your room-widget.model to below and let the consumer manage when it wants to subscribe, etc. (in this case, angular itself manages the subscription):

https://stackblitz.com/edit/angular-7r6ocu?file=src/app/room-widget.model.ts

import { timer, EMPTY } from 'rxjs';
import { map } from 'rxjs/operators';

export class RoomWidget {
  readonly elapsedTime$ = !this.sessionStartTime
    ? EMPTY
    : timer(0, 1000).pipe(
        map(_ => {
          const totalSeconds = Math.floor(
            (new Date().getTime() - this.sessionStartTime!.getTime()) / 1000
          );

          const hours = Math.floor(totalSeconds / 3600);
          const minutes = Math.floor(totalSeconds / 60) % 60;
          const seconds = totalSeconds % 60;

          return { hours, minutes, seconds };
        })
      );

  constructor(
    public readonly id: string,
    public readonly status: string,
    private readonly sessionStartTime?: Date
  ) {}
}
Related