Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unsubscribe multiple observables in angular component?

What is the best strategy to unsubscribe multiple observable in angular? Just to be clear I use this approach when the application is not big and do not need solutions such as ngrx that in this case would be an overengineering.

Currently I use a subscription instance to add all subscriptions and after that when the component was destroyed i call the unsubscribe method. But also I have seen alternatives using the takeUntil from rxjs.

export class MyComponent implements OnInit, OnDestroy {

  $firstObservable: Observable<number> = timer(0, 1000);
  $secondObservable: Observable<number> = timer(0, 1000);

  private _subscriptions = new Subscription();

  constructor() { }

  ngOnDestroy(): void {
    this._subscriptions .unsubscribe();
  }

  ngOnInit(): void {
    this._subscriptions .add(
      this.$firstObservable.subscribe(console.log));

    this._subscriptions .add(
      this.$secondObservable.subscribe(console.log));
  }

}

What would be the best solution?

like image 414
Renato Santos Avatar asked Mar 29 '19 12:03

Renato Santos


People also ask

How do I cancel observable subscription?

Use the unsubscribe method A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions. To prevent these memory leaks we have to unsubscribe from the subscriptions when we are done with. We do so by calling the unsubscribe method in the Observable.

Does Angular Async pipe unsubscribe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Do we need to unsubscribe observable in Angular?

🎩 Automagically Unsubscribe in Angular As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…


1 Answers

Subscribe class has an add method that adds multiple subscriptions into one and then it can be unsubscribed at once.

subscription1 = observable.subscribe(
    // next, err, complete etc
);

subscription2 = observable.subscribe(
    // next, err, complete etc
);

adding multiple subscriptions

subscription1.add(subscription2);

unsubscribing all subscriptions at once.

subscription1.unsubscribe();
like image 128
Aamer Shahzad Avatar answered Sep 23 '22 06:09

Aamer Shahzad