Created
July 11, 2019 22:28
-
-
Save alexeden/716a16d1ec7b855a37ad899c89c713b3 to your computer and use it in GitHub Desktop.
untilDestroyed Angular Component Operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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