Angular better way to clear subscriptions

Viewed 8694

There are many ways to handle multiple subscriptions efficiently in a component, I have 2 ways here and wanted to know which is more efficient and why??

Method 1: Using Array

Step 1: creating Array

private subscriptionArray: Subscription[];

Step 2: Adding subscriptions to the array

this.subscriptionArray.push(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
  this._toast.success('New store created');
}));

Step 3: iterating each subscription and unsubscribing

this.subscriptionArray.forEach(subs => subs.unsubscribe());

Method 2

Step 1: creating a new subscription

private subscriptions = new Subscription();

Step 2: Adding subscriptions

this.subscriptions.add(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
  this._toast.success('New store created');
  this._router.navigate(['/store-management']);
}));

Step3: Clearing subscription

this.subscriptions.unsubscribe();
6 Answers

You also have the third option, which is a custom RxJS operator.

I had created one and found out that Netanel Basal had found it too, so I'll give his clean code.

You can install UntilDestroyed or use the code :

function isFunction(value) {
  return typeof value === 'function';
}

export const untilDestroyed = (
  componentInstance,
  destroyMethodName = 'ngOnDestroy'
) => <T>(source: Observable<T>) => {
  const originalDestroy = componentInstance[destroyMethodName];
  if (isFunction(originalDestroy) === false) {
    throw new Error(
      `${
        componentInstance.constructor.name
      } is using untilDestroyed but doesn't implement ${destroyMethodName}`
    );
  }
  if (!componentInstance['__takeUntilDestroy']) {
    componentInstance['__takeUntilDestroy'] = new Subject();

    componentInstance[destroyMethodName] = function() {
      isFunction(originalDestroy) && originalDestroy.apply(this, arguments);
      componentInstance['__takeUntilDestroy'].next(true);
      componentInstance['__takeUntilDestroy'].complete();
    };
  }
  return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy']));
};

Then your subscriptions become

this.myService.subject.pipe(untilDestroyed(this)).subscribe(...);

Note that because of AOT compilation, you have to write a ngOnDestroy method, otherwise the operator isn't able to create it from scratch.

There's better, more succinct solution: https://www.npmjs.com/package/subsink by Ward Bell

export class SomeComponent implements OnDestroy {
  private subs = new SubSink();

  ...
  this.subs.sink = observable$.subscribe(...);
  this.subs.sink = observable$.subscribe(...);
  this.subs.sink = observable$.subscribe(...);
  ...

  // Unsubscribe when the component dies
  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}

I would prefer Method 2.

On Method 1 there is no problem.

It works perfectly fine. The problem with this approach is that we’re mixing observable streams with plain old imperative logic.

Method 2 is a built in mechanism to enhance this approach.

Read here

You have good answers provided though I would try to avoid all the above methods if possible and go for async 'pipe, that is allow angular do the subscription and unsubscription.

Lets consider a number of Observables say 5 observables

observale1$: Observable<IDataDto1>;
observale2$: Observable<IDataDto2>;
observale3$: Observable<IDataDto3>;
observale4$: Observable<IDataDto4>;
observale5$: Observable<IDataDto5>;

To avoid subscribing to all this we can create one single Observable say v$


import { forkJoin } from 'rxjs';
v$ = forkJoin({
  observale1: observale1$,
  observale2: observale2$,
  observale3: observale3$,
  observale4: observale4$,
  observale5: observale5$
});

With the above we can wrap our component.html in an *ngIf and allow angular to auto subscribe and unsubscribe


<ng-container *ngIf='v$ | async as v'>
  <!-- Your html code here -->
</ng-container>

Method 2 because Subscription.unsubscribe() does more than just seemingly unsubscribing, see its source code here.

e.g.


class SomeClass implements OnInit, OnDestroy { {

  // Setup your subscriptions
  private subscriptions = new Subscription();

  // Example Observable service
  constructor(private someService: SomeService) {}

  ngOnInit(): void {
    this.subscriptions.add(this.someService.getStuff());
    // ...
    this.subscriptions.add(/* etc */);
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }

} 
Related