Last active
February 3, 2020 19:25
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { interval, Observable } from 'rxjs'; | |
import { takeUntil } from 'rxjs/operators'; | |
import { subscribedContainerMixin } from '@my-scope/my-ng-lib/subscribed-container.mixin'; | |
@Component({ | |
selector: 'subscribed-container', | |
templateUrl: './subscribed-container.component.html' | |
}) | |
export class SubscribedContainerComponent extends subscribedContainerMixin() implements OnInit { | |
// We use interval because it does not complete. | |
observable$: Observable<number> = interval(1000); | |
subscription$$: Subscription; | |
ngOnInit(): void { | |
this.subscription$$ = this.observable$ | |
.pipe(tap(console.log), takeUntil(this.destroyed$)) | |
.subscribe(); | |
} | |
// If you need to do something on destroy in the component class. | |
// tslint:disable-next-line: use-lifecycle-interface | |
ngOnDestroy(): void { | |
// tslint:disable-next-line: no-unused-expression no-string-literal | |
super['ngOnDestroy'] && super['ngOnDestroy'](); | |
console.log('this.subscription$$.closed in ngOnDestroy::', this.subscription$$.closed); | |
} | |
} | |
Let's better compare the extra code necessary on each approach.
In my approach you have:
extends SubscribedContainer
super();
takeUntil(this.destroyed$)
I am taking your first approach since the second one implements OnDestroy
and the whole point of this is not to have to write that:
extends SubscribedContainer
observableSub = this.observable$.subscribe(/** whatever */);
destroySub = this.destroy$.subscribe(() => this.observableSub.unsubscribe());
super()
Not to mention that I do not like to see subscriptions before the constructor
.
I just made it into a mixin. Now it is scalable. You can extend the component from several mixins at the same time and you do not need to add super()
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would do it differently:
Or, without inheritance/mixin:
Note there are NO ASSUMPTIONS in that sample
Oh, and do count number of lines! All do the same thing. Less is more?
then take a step back, and imagine you are a beginning junior, which one would you be able to follow the easiest?