Skip to content

Instantly share code, notes, and snippets.

@kaplan81
Last active February 3, 2020 21:45
Show Gist options
  • Save kaplan81/cd67c96f24b33cb20f4bb5723308a8c3 to your computer and use it in GitHub Desktop.
Save kaplan81/cd67c96f24b33cb20f4bb5723308a8c3 to your computer and use it in GitHub Desktop.
import { OnDestroy } from '@angular/core';
import { Constructor } from '@my-scope/my-ng-lib/constructor';
import { Subject } from 'rxjs';
// WARNING: THIS DOES NOT WORK IN ANGULAR 8 WITH AOT!
// HOWEVER, IT DOES WORK IN ANGULAR 9!
/**
* Mixin class to automatically unsubscribe in component classes.
*
* // constructor.ts
* export type Constructor<T = {}> = new (...args: any[]) => T;
*/
export const subscribedContainerMixin = <T extends Constructor>(base: T = class {} as T) =>
class extends base implements OnDestroy {
destroyed$ = new Subject<void>();
/**
* DO NOT this.destroyed$.complete();
* It is not necessary:
* https://stackoverflow.com/questions/44289859/do-i-need-to-complete-a-subject-for-it-to-be-garbage-collected
*/
ngOnDestroy(): void {
this.destroyed$.next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment