|
7 | 7 | */ |
8 | 8 |
|
9 | 9 | import {EnvironmentInjector} from '../di'; |
| 10 | +import {isDestroyed} from '../render3/interfaces/type_checks'; |
10 | 11 | import {LView} from '../render3/interfaces/view'; |
11 | 12 | import {getLView} from '../render3/state'; |
12 | 13 | import {removeLViewOnDestroy, storeLViewOnDestroy} from '../render3/util/view_utils'; |
@@ -62,8 +63,28 @@ export class NodeInjectorDestroyRef extends DestroyRef { |
62 | 63 | } |
63 | 64 |
|
64 | 65 | override onDestroy(callback: () => void): () => void { |
65 | | - storeLViewOnDestroy(this._lView, callback); |
66 | | - return () => removeLViewOnDestroy(this._lView, callback); |
| 66 | + const lView = this._lView; |
| 67 | + |
| 68 | + // Checking if `lView` is already destroyed before storing the `callback` enhances |
| 69 | + // safety and integrity for applications. |
| 70 | + // If `lView` is destroyed, we call the `callback` immediately to ensure that |
| 71 | + // any necessary cleanup is handled gracefully. |
| 72 | + // With this approach, we're providing better reliability in managing resources. |
| 73 | + // One of the use cases is `takeUntilDestroyed`, which aims to replace `takeUntil` |
| 74 | + // in existing applications. While `takeUntil` can be safely called once the view |
| 75 | + // is destroyed — resulting in no errors and finalizing the subscription depending |
| 76 | + // on whether a subject or replay subject is used, replacing it with |
| 77 | + // `takeUntilDestroyed` introduces a breaking change, as it throws an error if |
| 78 | + // the `lView` is destroyed (https://github.com/angular/angular/issues/54527). |
| 79 | + if (isDestroyed(lView)) { |
| 80 | + callback(); |
| 81 | + // We return a "noop" callback, which, when executed, does nothing because |
| 82 | + // we haven't stored anything on the `lView`, and thus there's nothing to remove. |
| 83 | + return () => {}; |
| 84 | + } |
| 85 | + |
| 86 | + storeLViewOnDestroy(lView, callback); |
| 87 | + return () => removeLViewOnDestroy(lView, callback); |
67 | 88 | } |
68 | 89 | } |
69 | 90 |
|
|
0 commit comments