@ronas-it/dispose-bag
TypeScript icon, indicating that this package has built-in type declarations

1.1.6 • Public • Published

dispose-bag

A simple container for RxJs Subcriptions. It provides an easy way to unsubscribe from multiple subscriptions.

Installation

npm i dispose-bag

Usage

Basic usage

const disposeBag = new DisposeBag();

const subscription = new Subscription();

disposeBag.add(subscription);

disposeBag.unsubscribe();

Add subscription by call disposeBag.add(subscription). Call disposeBag.unsubscribe() to dispose of the resources held by all subscriptions in the bag.

const disposeBag = new DisposeBag();

const subscription = new Subscription();

disposeBag.add(subscription, 'subscription');

disposeBag.unsubscribe('subscription');

Also you can add named subscription by disposeBag.add(secondSubscription, 'subscription'). Call disposeBag.unsubscribe('subscription') to unsubscribe from named subscription.

Angular usage

Implement base component like this:

export class BaseComponent implements OnDestroy {
  protected disposeBag: DisposeBag;

  constructor() {
    this.disposeBag = new DisposeBag();
  }

  public ngOnDestroy(): void {
    this.disposeBag.unsubscribe();
  }
}

Extend your components by BaseComponent. And work with Observable like this:

public ngOnInit(): void {
  this.disposeBag.add(
    this.aircraftsService
      .aircraftsLoaded
      .subscribe((aircrafts) => {
        this.aircrafts = aircrafts;
        this.loading = false;
      })
  );

  this.disposeBag.add(
    this.aircraftsService
      .aircraftsPageChanged
      .subscribe((page) => this.currentPage = page)
  );

  this.disposeBag.add(
    this.aircraftsService
      .aircraftsTotalItemsChanged
      .subscribe((totalItems) => this.totalItems = totalItems)
  );
}

NOTE

So you DON'T NEED manually unsubscribe in ngOnDestroy in this way:

public ngOnDestroy(): void {
  if (this.aircraftsLoadedSubscription) {
    this.aircraftsLoadedSubscription.unsubscribe();
  }

  if (this.aircraftsPageChangedSubscription) {
    this.aircraftsPageChangedSubscription.unsubscribe();
  }

  if (this.aircraftsTotalItemsChangedSubscription) {
    this.aircraftsTotalItemsChangedSubscription.unsubscribe();
  }

  if (this.aircraftDeletedSubscription) {
    this.aircraftDeletedSubscription.unsubscribe();
  }

  if (this.paginationPageChangedSubscription) {
    this.paginationPageChangedSubscription.unsubscribe();
  }
}

Package Sidebar

Install

npm i @ronas-it/dispose-bag

Weekly Downloads

1

Version

1.1.6

License

ISC

Unpacked Size

5.24 kB

Total Files

6

Last publish

Collaborators

  • ipakhomov
  • eleonov
  • astorozhevsky
  • opikhnenko
  • dmitryusenko