@badisi/ngx-safe-subscribe
Version:
Easy way to automatically unsubscribe from RxJS observables in Angular components
38 lines (34 loc) • 1.34 kB
JavaScript
import { Subscription, Observable } from 'rxjs';
const HAS_DECORATOR = Symbol('__safeSubscribeDecorator');
const SUBSCRIPTION = Symbol('__safeSubscribeSubscription$');
function SafeSubscribe(destructorName = 'ngOnDestroy') {
return (classType) => {
const originalDestroy = classType.prototype[destructorName];
classType.prototype[destructorName] = function () {
originalDestroy && originalDestroy.call(this);
this[SUBSCRIPTION]?.unsubscribe();
this[SUBSCRIPTION] = null;
};
classType.prototype[HAS_DECORATOR] = true;
};
}
function safeSubscribe(target, ...args) {
const sub = this.subscribe(...args);
if (target) {
const hasDecorator = Object.getPrototypeOf(target)[HAS_DECORATOR];
if (!hasDecorator) {
throw new Error(`${target.constructor.name} class must be decorated with @SafeSubscribe() otherwise Observable<T>.safeSubscribe() will have no effect.`);
}
if (!target[SUBSCRIPTION]) {
target[SUBSCRIPTION] = new Subscription();
}
target[SUBSCRIPTION].add(sub);
}
return sub;
}
Observable.prototype.safeSubscribe = safeSubscribe;
/**
* Generated bundle index. Do not edit.
*/
export { SafeSubscribe, safeSubscribe };
//# sourceMappingURL=badisi-ngx-safe-subscribe.mjs.map