npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ng-rxjs-safe-subscribe

v18.0.0

Published

Implementation of Angular's repeatable OnDestroy pattern with RxJS observables

Downloads

89

Readme

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.

What about Signals?

Signals can be an answer to this kind of issue. If you just want to provide a value from rxjs Observable, consider using Signals.

Compatibility

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

| ng-rxjs-safe-subscribe | Angular | RxJS | | ---------------------- | ------- | ----- | | 18.x.x | 18.x.x | 7.x.x | | 17.x.x | 17.x.x | 7.x.x | | 16.x.x | 16.x.x | 7.x.x | | 15.x.x | 15.x.x | 7.x.x | | 14.x.x | 14.x.x | 7.x.x | | 13.x.x | 13.x.x | 7.x.x | | 12.x.x | 12.x.x | 6.x.x | | 11.x.x | 11.x.x | 6.x.x | | 10.x.x | 10.x.x | 6.x.x |

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

License

ISC