Wednesday, 24 November 2021

Automatically Unsubscribe in Angular Component


let isFunction = fn => typeof fn === "function";

const doUnsubscribe = subscription => {
subscription &&
isFunction(subscription.unsubscribe) &&
subscription.unsubscribe();
};

const doUnsubscribeIfArray = subscriptionsArray => {
Array.isArray(subscriptionsArray) &&
subscriptionsArray.forEach(doUnsubscribe);
};

export function AutoUnsubscribe({
blackList = [],
arrayName = "",
event = "ngOnDestroy"
} = {}) {
return function(constructor: Function) {
const original = constructor.prototype[event];

if (!isFunction(original)) {
throw new Error(
`${
constructor.name
} is using @AutoUnsubscribe but does not implement ${event}`
);
}

constructor.prototype[event] = function() {
isFunction(original) && original.apply(this, arguments);
if (arrayName) {
doUnsubscribeIfArray(this[arrayName]);
return;
}
for (let propName in this) {
if (blackList.includes(propName)) continue;
const property = this[propName];
doUnsubscribe(property);
}
};
};
} 

//@AutoUnsubscribe() // use if direct property
@AutoUnsubscribe({ // use if you have array of subscriptions
arrayName:"subscriptions"
})
@Component({
selector: 'inbox'
})
export class InboxComponent {
one: Subscription;
two: Subscription;
subscription: [];
constructor( private store: Store<any>, private element : ElementRef ) {}

ngOnInit() {
this.one = store.select("data").subscribe(data => // do something);
this.two = Observable.interval.subscribe(data => // do something);

// this.subscriptions = [
// onResizeSubscription,
// deploymentSubscription,
// patientIdSubscription,
// createQuestionnaireLoadedSubscription,
// errorCreateQeustionnaireSubscription,
// ];
}

// This method must be present, even if empty.
ngOnDestroy() {
// We'll throw an error if it doesn't
}
}

No comments:

Post a Comment