unsubscribe-decorator
Version:
A decorator to unsubscribe from RxJs observables
37 lines • 1.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Unsubscribe = void 0;
const takeUntil_1 = require("rxjs/internal/operators/takeUntil");
const Subject_1 = require("rxjs/internal/Subject");
function Unsubscribe(params) {
return function (target, propertyKey) {
params = {
destroyFunc: 'ngOnDestroy',
...params
};
const destroy$ = new Subject_1.Subject();
let observable;
Object.defineProperty(target, propertyKey, {
get() {
return observable;
},
set(val) {
observable = val.pipe(takeUntil_1.takeUntil(destroy$));
}
});
if (typeof target[params.destroyFunc] !== 'function') {
throw new Error(`${target.constructor.name} must implement ${params.destroyFunc}() lifecycle hook`);
}
target[params.destroyFunc] = ngOnDestroyDecorator(target[params.destroyFunc]);
function ngOnDestroyDecorator(f) {
return function () {
destroy$.next();
destroy$.complete();
return f.apply(target, arguments);
};
}
return target;
};
}
exports.Unsubscribe = Unsubscribe;
//# sourceMappingURL=unsubscribe-decorator.js.map