Let me explain how the until-destroy library works. It provides two main pieces - a @UntilDestroy() decorator and an untilDestroyed() operator - that work together to automatically unsubscribe from RxJS subscriptions when an Angular component/directive/pipe is destroyed.
Here's the algorithm:
The @UntilDestroy() decorator:
Decorates the class prototype with a special symbol (DECORATOR_APPLIED) to mark it as handled
Overrides the class's ngOnDestroy method (or pipe's onDestroy) to handle cleanup
The enhanced destroy method will:
Call the original destroy method if it exists
Complete any subject associated with the instance
Optionally unsubscribe from subscriptions stored in an array if arrayName option is provided
Optionally check all properties and unsubscribe any subscriptions if checkProperties is true
The untilDestroyed() operator:
Creates a Subject on the instance using a unique symbol as the key
In development mode, sets up a checker to warn if subscriptions aren't properly cleaned up
Returns an Observable that uses RxJS takeUntil() operator with the destroy Subject
When the component is destroyed, the Subject emits and completes, triggering unsubscription
The key parts of the implementation:
typescript
// Decorator enhances ngOnDestroy
function decorateNgOnDestroy(ngOnDestroy, options) {
return function() {
ngOnDestroy?.call(this);
completeSubjectOnTheInstance(this, getSymbol());
if (options.arrayName) {
unsubscribeIfPropertyIsArrayLike(this[options.arrayName]);
}
if (options.checkProperties) {
for (const property in this) {
unsubscribe(this[property]);
}
}
};
}
// Operator sets up subscription management
export function untilDestroyed(instance, destroyMethodName?) {
return source => {
const symbol = getSymbol(destroyMethodName);
createSubjectOnTheInstance(instance, symbol);
return source.pipe(takeUntil(instance[symbol]));
};
}
The library is quite flexible:
It can work with Angular components/directives/pipes using the decorator pattern
It can work with regular classes by specifying a custom destroy method name
It provides options to:
Check all properties for subscriptions
Target a specific array of subscriptions
Blacklist certain properties from being checked
The implementation is also careful to:
Preserve original destroy method behavior
Handle inheritance correctly
Provide development mode checks
Clean up properly to prevent memory leaks
Support multiple subscriptions per instance
Work correctly with Angular's dependency injection system
This provides a robust solution for managing RxJS subscription cleanup in Angular applications.
The destroyMethodName parameter is used when you want to use untilDestroyed with non-Angular classes that have their own cleanup method. Here's how it works:
For Angular Components/Directives/Pipes:
typescript
@UntilDestroy()
@Component({...})
class MyComponent {
data$ = someObservable$.pipe(
untilDestroyed(this) // No destroyMethodName needed - uses ngOnDestroy
).subscribe();
}
From the code, we can see the different behavior based on whether destroyMethodName is provided:
typescript
export function untilDestroyed<T>(instance: T, destroyMethodName?: keyof T) {
return <U>(source: Observable<U>) => {
const symbol = getSymbol<T>(destroyMethodName);
// Non-Angular class case
if (typeof destroyMethodName === 'string') {
overrideNonDirectiveInstanceMethod(instance, destroyMethodName, symbol);
}
// Angular class case
else {
NG_DEV_MODE && ensureClassIsDecorated(instance);
createSubjectOnTheInstance(instance, symbol);
}
const destroy$: Subject<void> = (instance as any)[symbol];
return source.pipe(takeUntil<U>(destroy$));
};
}
For non-Angular classes, it calls overrideNonDirectiveInstanceMethod:
typescript
function overrideNonDirectiveInstanceMethod(
instance: any,
destroyMethodName: string,
symbol: symbol
): void {
const originalDestroy = instance[destroyMethodName];
// Verify the destroy method exists
if (NG_DEV_MODE && typeof originalDestroy !== 'function') {
throw new Error(
`${instance.constructor.name} is using untilDestroyed but doesn't implement ${destroyMethodName}`
);
}
createSubjectOnTheInstance(instance, symbol);
// Override the destroy method
instance[destroyMethodName] = function () {
originalDestroy.apply(this, arguments);
completeSubjectOnTheInstance(this, symbol);
instance[destroyMethodName] = originalDestroy;
};
}
The key scenarios for using destroyMethodName are:
Regular Classes: When you have a non-Angular class that needs to clean up subscriptions
Custom Cleanup Methods: When you want to use a different method name than ngOnDestroy
Framework-Agnostic Code: When writing code that might be used outside of Angular
Testing: When you need more control over when cleanup occurs
The library's tests show these scenarios:
typescript
class Test {
subscription!: Subscription;
destroy() {} // Custom destroy method
subscribe(spy: ReturnType<typeof createObserver>) {
this.subscription = new Subject()
.pipe(untilDestroyed(this, 'destroy'))
.subscribe(spy);
}
}
This flexibility makes the library useful both within and outside of Angular applications, while maintaining proper cleanup behavior in both contexts.
The library adds a unique Subject to each instance by using a Symbol as a property key and adding the Subject directly to the instance (not the prototype). Here's how it works:
First, it generates a unique symbol for the property key:
typescript
// From internals.ts
const DESTROY: unique symbol = Symbol('__destroy');
export function getSymbol<T>(destroyMethodName?: keyof T): symbol {
if (typeof destroyMethodName === 'string') {
return Symbol(`__destroy__${destroyMethodName}`);
} else {
return DESTROY;
}
}
Then it creates a new Subject for each instance:
typescript
export function createSubjectOnTheInstance(instance: any, symbol: symbol): void {
if (!instance[symbol]) {
instance[symbol] = new Subject<void>();
}
}
The key points are:
Using a Symbol as the property key ensures no naming collisions
The Subject is added directly to the instance object, not the prototype
Each instance gets its own unique Subject instance
Here's an example of how this works:
typescript
// Example usage
@UntilDestroy()
class MyComponent {
constructor() {
someObservable$.pipe(untilDestroyed(this)).subscribe();
}
}
const instance1 = new MyComponent();
const instance2 = new MyComponent();
// Under the hood, the library does something like:
const symbol = Symbol('__destroy');
instance1[symbol] = new Subject<void>(); // Unique Subject for instance1
instance2[symbol] = new Subject<void>(); // Different Subject for instance2
The library also handles multiple calls to untilDestroyed on the same instance:
typescript
class MyClass {
// These will use the same Subject because they use the same destroy method
sub1 = obs1$.pipe(untilDestroyed(this, 'destroy')).subscribe();
sub2 = obs2$.pipe(untilDestroyed(this, 'destroy')).subscribe();
// This will use a different Subject because it uses a different destroy method
sub3 = obs3$.pipe(untilDestroyed(this, 'cleanup')).subscribe();
}
This is handled by creating different symbols for different destroy method names:
typescript
// Different destroy methods get different symbols
const symbol1 = Symbol('__destroy__destroy'); // For 'destroy' method
const symbol2 = Symbol('__destroy__cleanup'); // For 'cleanup' method
instance[symbol1] = new Subject<void>(); // For subs using 'destroy'
instance[symbol2] = new Subject<void>(); // For subs using 'cleanup'
This approach ensures that:
Each instance has its own Subject(s)
Multiple subscriptions on the same instance can share a Subject
Different destroy methods on the same instance get different Subjects
The Subjects are properly cleaned up when the instance is destroyed
The use of Symbols and instance properties (rather than prototype properties) makes this possible while maintaining proper isolation between instances.