17.0.0 • Published 5 months ago

ng-rxjs-safe-subscribe v17.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

Why do I need it?

Because of the DRY principle. Instead of reimplementing the pattern in every component:

export class MyComponent implements OnDestroy {
  private booksSubscription: Subscription;

  getBooks(): void {
    this.booksSubscription = this.booksService.getBooks().subscribe((books) =>
      (...)
    );
  }

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

simplify the code and just subscribe safely:

export class MyComponent extends RxjsOnDestroy {
  getBooks(): void {
    this.booksService.getBooks().subscribeSafely(this, (books) =>
      (...)
    );
  }
}

One of the most common mistakes made with RxJS is subscribing to an Observable in a fire-and-forget manner.

A rule of thumb is that a subscriber should unsubscribe when no longer using an observable. If there is no explicit unsubscribe, then those books will be pushed to subscribe function infinitely. While it may not be the case for some observable sources, it can silently become an issue and cause a leaks leading to unwanted behaviors.

There are a few ways to deal with unsubscribing. A direct:

  1. calling unsubscribe() directly on subscription.

... or more declarative one using RxJs:

  1. using operator: takeUntil, takeWhile (declarative unsubscribe),
  2. taking a finite number of values: first, take(n) - it'll unsubscribe after n emits, and only then,
  3. async pipe in HTML template - takes care of the issue automagically.

Package ng-rxjs-safe-subscribe provides a ready-to-use solution for every Angular project.

Installation

Install ng-rxjs-safe-subscribe from npm:

npm install ng-rxjs-safe-subscribe

Import an abstract class:

import { RxjsOnDestroy } from 'ng-rxjs-safe-subscribe';

Extend the class with RxjsOnDestroy that implements the OnDestroy hook.

export class AppComponent extends RxjsOnDestroy

Finally, use one of the following approaches to subscribe in code using Observable.subscribeSafely or Observable.subscribeUntil function.

How to execute custom logic at ngOnDestroy

Consider passing an arrow function with custom destroy logic to the constructor:

    constructor() {
        super(() => this.customDestroy());
    }

The ngOnDestroy function can be also easily overridden, but be sure to always call the base function for RxjsOnDestroy to unsubscribe properly:

    override ngOnDestroy(){
        super.ngOnDestroy();

        ...
    }

Typescript can help you avoid mistaken overrides with noImplicitOverride rule. It is HIGHLY RECOMMENDED to enable that.

1. Unsubscribe with a sink

Subscribe safely, pass an object which extends RxjsOnDestroy abstract class:

this.users$.subscribeSafely(rxjsOnDestroyInstance, (x) => console.log(x));

Full example:

import { Component } from '@angular/core';
import { RxjsOnDestroy } from 'ng-rxjs-safe-subscribe';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent extends RxjsOnDestroy {
  users$: Observable<User[]>;

  constructor(private userService: UserService) {
    super();

    this.users$ = this.userService.getUsers();
    this.users$.subscribeSafely(this, (x) => console.log(x));
  }
}

2. Declarative unsubscribe

You may pass an observable instance that triggers unsubscribe by passing a value and completion:

this.users$.subscribeUntil(this.destroy$, (x) => console.log(x));

The example uses this.destroy$ of RxjsOnDestroy class.

Full example:

import { Component } from '@angular/core';
import { RxjsOnDestroy } from 'ng-rxjs-safe-subscribe';
import { Observable, fromEvent, merge } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent extends RxjsOnDestroy {
  users$: Observable<User[]>;

  constructor(private userService: UserService) {
    super();

    this.users$ = this.userService.getUsers();

    const cancelBtn = this.element.querySelector('.cancel-button');
    const cancel$ = fromEvent(cancelBtn, 'click');
    const stop$ = merge(cancel$, this.destroy$)

    // will stop when button clicked or component destroyed
    this.users$.subscribeUntil(stop$, (x) => console.log(x));

    // will stop when component destroyed
    this.users$.subscribeUntil(this.destroy$, (x) => console.log(x));
 }
}

You can now use stop to kill the subscription in the moment of your choosing, but remember to always unsubscribe on object destruction.

Read up Ben Lesh's article for more on this topic.

Compatibility

The only two dependencies are Angular and RxJS. Here is the versions compatibility list:

ng-rxjs-safe-subscribeAngularRxJS
17.x.x17.x.x7.x.x
16.x.x16.x.x7.x.x
15.x.x15.x.x7.x.x
14.x.x14.x.x7.x.x
13.x.x13.x.x7.x.x
12.x.x12.x.x6.x.x
11.x.x11.x.x6.x.x
10.x.x10.x.x6.x.x

The package should work with every version of Angular, as long as the RxJS version is matching yours.

License

ISC

17.0.0

5 months ago

16.0.0

5 months ago

15.0.0

1 year ago

14.0.3

2 years ago

14.0.0

2 years ago

14.0.1

2 years ago

14.0.2

2 years ago

13.0.0

2 years ago

13.0.1

2 years ago

12.0.2

3 years ago

13.0.0-next.0

3 years ago

12.0.1

3 years ago

12.0.0

3 years ago

10.0.5

3 years ago

12.0.0-next.4

3 years ago

9.0.3

3 years ago

10.0.4

3 years ago

11.0.4

3 years ago

11.0.5

3 years ago

12.0.0-next.3

3 years ago

10.0.3

3 years ago

9.0.2

3 years ago

10.0.2

3 years ago

11.0.3

3 years ago

12.0.0-next.2

3 years ago

12.0.0-next.1

3 years ago

11.0.2

3 years ago

9.0.1

3 years ago

10.0.1

3 years ago

11.0.1

3 years ago

12.0.0-next.0

3 years ago

12.0.0-next

3 years ago

11.0.0

3 years ago

10.0.0

3 years ago

9.0.0

3 years ago