|
1 |
| -import { AfterViewInit, Directive, Injectable, Input, OnInit } from '@angular/core'; |
| 1 | +import { AfterViewInit, Directive, Injectable, Input, OnDestroy, OnInit } from '@angular/core'; |
2 | 2 | import { Event, NavigationEnd, NavigationStart, Router } from '@angular/router';
|
3 | 3 | import { getCurrentHub } from '@sentry/browser';
|
4 | 4 | import { Span, Transaction, TransactionContext } from '@sentry/types';
|
5 | 5 | import { logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
|
6 |
| -import { Observable } from 'rxjs'; |
| 6 | +import { Observable, Subscription } from 'rxjs'; |
7 | 7 | import { filter, tap } from 'rxjs/operators';
|
8 | 8 |
|
9 | 9 | let instrumentationInitialized: boolean;
|
@@ -53,7 +53,7 @@ export function getActiveTransaction(): Transaction | undefined {
|
53 | 53 | * Creates a new transaction for every route change and measures a duration of routing process.
|
54 | 54 | */
|
55 | 55 | @Injectable({ providedIn: 'root' })
|
56 |
| -export class TraceService { |
| 56 | +export class TraceService implements OnDestroy { |
57 | 57 | public navStart$: Observable<Event> = this._router.events.pipe(
|
58 | 58 | filter(event => event instanceof NavigationStart),
|
59 | 59 | tap(event => {
|
@@ -100,10 +100,19 @@ export class TraceService {
|
100 | 100 | );
|
101 | 101 |
|
102 | 102 | private _routingSpan?: Span;
|
| 103 | + private _subscription: Subscription = new Subscription(); |
103 | 104 |
|
104 | 105 | public constructor(private readonly _router: Router) {
|
105 |
| - this.navStart$.subscribe(); |
106 |
| - this.navEnd$.subscribe(); |
| 106 | + this._subscription.add(this.navStart$.subscribe()); |
| 107 | + this._subscription.add(this.navEnd$.subscribe()); |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * This is used to prevent memory leaks when the root view is created and destroyed multiple times, |
| 112 | + * since `subscribe` callbacks captures `this` and prevent many resources from being GC'd. |
| 113 | + */ |
| 114 | + public ngOnDestroy(): void { |
| 115 | + this._subscription.unsubscribe(); |
107 | 116 | }
|
108 | 117 | }
|
109 | 118 |
|
|
0 commit comments