0
votes

I have class/service where I close all subscriptions inside other App Classes like this:

private shutdown() {

this.service1.destroy();
this.service2.destroy();
......
......
this.serviceN.destroy();
this.stopApp();

}

And inside every service/class I use the subscription like this:

private unsubscribe = new Subject();

ngOnInit() {
  this.heroService.getHeroes()
                  .takeUntil(this.unsubscribe)
                  .subscribe(
                     heroes => this.heroes = heroes,
                     error =>  this.errorMessage = <any>error);
}

onSelectVillain(event) {
  this.villainService.getVillains()
                     .takeUntil(this.unsubscribe)
                     .subscribe(
                     .....
}

destroy(){
    this.unsubscribe.next();
    this.unsubscribe.complete();
}

I want to optimise this code and remove all these destroy fnctions/calls. I though about adding a static subject in the closing class and calling it in the other classes/services. Like this:

  public static unsubscribeEverywhere$ = new Subject<void>();
  .....
  private shutdown() {

  this.destroy();
  this.stopApp();
  }

  ......
  destroy() {
    this.unsubscribeEverywhere$.next();
    this.unsubscribeEverywhere$.complete();
  }

And in the other classe, I do like this:

ngOnInit() {
  this.heroService.getHeroes()
                  .takeUntil(ClosingClass.unsubscribeEverywhere)
                  .subscribe(
                     heroes => this.heroes = heroes,
                     error =>  this.errorMessage = <any>error);
}

onSelectVillain(event) {
  this.villainService.getVillains()
                     .takeUntil(ClosingClass.unsubscribeEverywhere)
                     .subscribe(
                     .....
}

Is this is a good solution/alternative ? If not what is the best way to improve the implementation ?