Skip to content

takeUntilDestroyed might not work as expected in certain situations #49658

@yjaaidi

Description

@yjaaidi

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

The current implementation of takeUntilDestroyed() operator assumes that the operator is used before the component is destroyed.
If the operator is used after the component is destroyed then it will not unsubscribe as expected and observables might leak.

Here is an example of misuse where this can happen:

class MyCmp {
 destroyRef = inject(DestroyRef);
 ngOnDestroy() {
  setTimeout(() => source$.pipe(takeUntilDestroyed(this.destroyRef).subscribe());
 }
}

While in most cases, this wouldn't happen as the injection context would be missing... but then we can pass a destroyRef manually like in the example above.

Cf.

const destroyed$ = new Observable<void>(observer => {
destroyRef!.onDestroy(observer.next.bind(observer));
});

It might be interesting to add a isDestroyed property on DestroyRef for late subscriber use cases like takeUntilDestroyed() usage above.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

Angular 16.0.0-next.5

Anything else?

No response

Metadata

Metadata

Labels

P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: coreIssues related to the framework runtimebug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions