ng-rxjs-safe-subscribe
v19.0.0
Published
Implementation of Angular's repeatable OnDestroy pattern with RxJS observables
Downloads
334
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:
- calling unsubscribe() directly on subscription.
... or more declarative one using RxJs:
- using operator: takeUntil, takeWhile (declarative unsubscribe),
- taking a finite number of values: first, take(n) - it'll unsubscribe after n emits, and only then,
- 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 | | ---------------------- | ------- | ------------------ | | 19.x.x | 19.x.x | ^6.5.3 || ^7.4.0 | | 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.