Based on edit3 here I implemented that solution. But do that Subject initialisation and "clean up" in ngOnDestroy in every component is still pain. I thought that it could be passed to decorator, eg. based on this post:
export function AutoUnsubscribe( constructor ) {
const original = constructor.prototype.ngOnDestroy;
constructor.prototype.ngUnsubscribe = new Subject<void>();
constructor.prototype.ngOnDestroy = function () {
constructor.prototype.ngUnsubscribe.next();
constructor.prototype.ngUnsubscribe.complete();
original && typeof original === "function" && original.apply(this, arguments);
};
}
Usage is just like any other class decorator. And it works well, but I had to hack type system when using it, like this: takeUntil((this as any).ngUnsubscribe)
.
The property ngUnsubscribe is unrecognised by the type system in a component. Is there any way to tell the type system that this property is there or will be?
If this would be possible then it would be super easy to use this @AutoUnsubscribe decorator: just decorate a class and put takeUntil(this.ngUnsubscribe) before every subscribe. Wonder if we can do even better to just decorate a class and automagically this decorator would put takeUntil(this.ngUnsubscribe) before every subscribe for us.
My current workaround is to use BaseComponent with ngUnsubscribe prop. and extend every component which calls subscribe.