Skip to content

fix(angular): prevent memory leak when the root view is removed #3594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions packages/angular/src/tracing.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { AfterViewInit, Directive, Injectable, Input, OnInit } from '@angular/core';
import { AfterViewInit, Directive, Injectable, Input, OnDestroy, OnInit } from '@angular/core';
import { Event, NavigationEnd, NavigationStart, Router } from '@angular/router';
import { getCurrentHub } from '@sentry/browser';
import { Span, Transaction, TransactionContext } from '@sentry/types';
import { logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
import { Observable } from 'rxjs';
import { Observable, Subscription } from 'rxjs';
import { filter, tap } from 'rxjs/operators';

let instrumentationInitialized: boolean;
Expand Down Expand Up @@ -53,7 +53,7 @@ export function getActiveTransaction(): Transaction | undefined {
* Creates a new transaction for every route change and measures a duration of routing process.
*/
@Injectable({ providedIn: 'root' })
export class TraceService {
export class TraceService implements OnDestroy {
public navStart$: Observable<Event> = this._router.events.pipe(
filter(event => event instanceof NavigationStart),
tap(event => {
Expand Down Expand Up @@ -100,10 +100,19 @@ export class TraceService {
);

private _routingSpan?: Span;
private _subscription: Subscription = new Subscription();

public constructor(private readonly _router: Router) {
this.navStart$.subscribe();
this.navEnd$.subscribe();
this._subscription.add(this.navStart$.subscribe());
this._subscription.add(this.navEnd$.subscribe());
}

/**
* This is used to prevent memory leaks when the root view is created and destroyed multiple times,
* since `subscribe` callbacks captures `this` and prevent many resources from being GC'd.
*/
public ngOnDestroy(): void {
this._subscription.unsubscribe();
}
}

Expand Down