Skip to content

Instantly share code, notes, and snippets.

@alexeden
Created July 11, 2019 22:28
Show Gist options
  • Select an option

  • Save alexeden/716a16d1ec7b855a37ad899c89c713b3 to your computer and use it in GitHub Desktop.

Select an option

Save alexeden/716a16d1ec7b855a37ad899c89c713b3 to your computer and use it in GitHub Desktop.
untilDestroyed Angular Component Operator
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export const untilDestroyed = <C extends any>(
componentInstance: C,
destroyMethodName = 'ngOnDestroy'
) => <T>(source: Observable<T>) => {
const originalDestroy = componentInstance[destroyMethodName];
if (typeof originalDestroy !== 'function') {
throw new Error(
`${
componentInstance.constructor.name
} is using untilDestroyed but doesn't implement ${destroyMethodName}`
);
}
if (!componentInstance['__takeUntilDestroy']) {
componentInstance['__takeUntilDestroy'] = new Subject();
componentInstance[destroyMethodName] = function(this: C) {
typeof originalDestroy === 'function' && originalDestroy.apply(this, arguments);
componentInstance['__takeUntilDestroy'].next(true);
componentInstance['__takeUntilDestroy'].complete();
};
}
return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy']));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment