Skip to content

Commit

Permalink
feat: create untilDestroyed pipeable operator
Browse files Browse the repository at this point in the history
  • Loading branch information
webdevius committed Mar 18, 2018
1 parent e692570 commit ffc98ea
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/take-until-destory.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Subject } from 'rxjs/Subject';
import { Observable } from "rxjs/Observable";
import { Observable } from 'rxjs/Observable';
import { takeUntil } from 'rxjs/operators';

export interface OnDestroy {
readonly destroyed$: Observable<boolean>;
readonly destroyed$?: Observable<boolean>;
ngOnDestroy(): void;
}

Expand All @@ -16,28 +17,28 @@ function isFunction( value ) {
}

/**
*
* @param destroyMethodName
*
* @param destroyMethodName
*/
export function TakeUntilDestroy(destroyMethodName = 'ngOnDestroy') {

return function<T extends { new( ...args: any[] ): {} }>(constructor: T) {

const originalDestroy = constructor.prototype[destroyMethodName];

if( !isFunction(originalDestroy) ) {
console.warn(`${constructor.name} is using @TakeUntilDestroy but does not implement ${destroyMethodName}`);
}

return class extends constructor {

/**
*
* @type {Subject<any>}
* @private
*/
_takeUntilDestroy$: Subject<boolean> = new Subject();

/**
*
* @returns {Observable<boolean>}
Expand All @@ -46,7 +47,7 @@ export function TakeUntilDestroy(destroyMethodName = 'ngOnDestroy') {
this._takeUntilDestroy$ = this._takeUntilDestroy$ || new Subject();
return this._takeUntilDestroy$.asObservable();
}

/**
* Call the super destroyMethodName method and clean the observers
*/
Expand All @@ -58,3 +59,12 @@ export function TakeUntilDestroy(destroyMethodName = 'ngOnDestroy') {
}
}
}

export const untilDestroyed = that => <T>(source: Observable<T>) => {
if (!('destroyed$' in that)) {
console.warn(`'destroyed$' property does not exist on ${that.constructor.name}. Did you decorate the class with '@TakeUntilDestroy()'?`);
return source;
}

return source.pipe(takeUntil<T>(that.destroyed$));
};

0 comments on commit ffc98ea

Please sign in to comment.