ng-auto-unsubscribe
Version:
A utility base class for Angular to auto-unsubscribe from observables
99 lines (94 loc) • 3.16 kB
JavaScript
import * as i0 from '@angular/core';
import { inject, DestroyRef, Directive } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
/**
* Abstract base class for angular components.
* Automatically unsubscribe from RxJS observables when components destroyed, using Angular's
* built-in `DestroyRef` and `takeUntilDestroyed`.
*
* Extend this class in your component to gain access to
* convenient helper methods for automatic unsubscription.
*
* Example usage:
* ```ts
* @Component({...})
* export class MySpecialComponent extends NgAutoUnsubscribe {
* ngOnInit() {
* this.streamUntil(this.myObservable$)
* .subscribe(value => {
* // handle value here
* });
* this.myObservable$
* .pipe(this.until())
* .subscribe(value => {
* // handle value here
* });
* }
* }
* ```
*
* Note: Requires Angular 16+ for `DestroyRef` and `takeUntilDestroyed`.
*/
class NgAutoUnsubscribe {
/** Injected Angular DestroyRef for unsubscription */
destroyRef = inject(DestroyRef);
/**
* Returns an operator function that applies `takeUntilDestroyed`
* for automatic unsubscription.
*
* Usage:
* ```ts
* observable$.pipe(this.until()).subscribe();
* ```
*/
until() {
return takeUntilDestroyed(this.destroyRef);
}
/**
* Takes an observable and returns a new observable
* that automatically unsubscribes on destroy.
*
* Usage:
* ```ts
* this.streamUntil(observable$).subscribe();
* ```
*/
streamUntil(observable$) {
return observable$.pipe(takeUntilDestroyed(this.destroyRef));
}
/**
* Subscribes to an observable and invokes a callback for each emitted value,
* automatically unsubscribing when the component or service is destroyed.
*
* This is a shorthand for `.pipe(takeUntilDestroyed()).subscribe(callback)`
* to reduce boilerplate in components or services.
*
* @param observable$ The observable to subscribe to.
* @param callback Function to handle emitted values.
*
* Usage:
* ```ts
* this.watchUntil(this.myObservable$, value => {
* // handle value here
* });
* ```
*/
watchUntil(observable$, callback) {
observable$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((valueFromObs) => callback(valueFromObs));
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.11", ngImport: i0, type: NgAutoUnsubscribe, deps: [], target: i0.ɵɵFactoryTarget.Directive });
static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.11", type: NgAutoUnsubscribe, isStandalone: true, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.11", ngImport: i0, type: NgAutoUnsubscribe, decorators: [{
type: Directive
}] });
/*
* Public API Surface of ng-auto-unsubscribe
*/
/**
* Generated bundle index. Do not edit.
*/
export { NgAutoUnsubscribe };
//# sourceMappingURL=ng-auto-unsubscribe.mjs.map