Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better onDestroy mechanism #5564

Open
vthinkxie opened this issue Jul 15, 2020 · 2 comments
Open

better onDestroy mechanism #5564

vthinkxie opened this issue Jul 15, 2020 · 2 comments

Comments

@vthinkxie
Copy link
Member

current way

  private destroy$ = new Subject();
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

better way

extends subject

ref https://stackblitz.com/edit/angular-auto-unsubscribe-service?file=src%2Fapp%2Fhello.component.ts

@Injectable()
export class NgOnDestroy extends Subject<null> implements OnDestroy {
  ngOnDestroy() {
    this.next();
    this.complete();
  }
}

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  providers: [ NgOnDestroy ]
})
export class HelloComponent implements OnInit {
  @Input() name: string;

  constructor(@Self() private ngOnDestroy$: NgOnDestroy) {}

  ngOnInit() {
    this.ngOnDestroy$.subscribe().add(() => console.log('Destroyed!'));
  }
}

extends Obseverable

https://twitter.com/Waterplea/status/1271037735332204544

@vthinkxie vthinkxie changed the title better on destroy mechanism better onDestroy mechanism Jul 15, 2020
@Airblader
Copy link
Collaborator

This is interesting, but why exactly is it "better" or performance related? It doesn't really save any code, nor changes what actually happens. In fact it creates more runtime overhead by creating more objects.

Another alternative is a OnceSubject which has a single method for next + complete, that would also save a bit of code when used.

@cipchk
Copy link
Member

cipchk commented Oct 10, 2020

建议作为 import { NgOnDestroy } from 'ng-zorro-antd/core/xxxx' 的一部分。

@hsuanxyz hsuanxyz added this to the v11.0.0 milestone Oct 23, 2020
@hsuanxyz hsuanxyz modified the milestones: v11.0.0, backlog Jun 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants