Skip to content

Instantly share code, notes, and snippets.

@eneajaho
Created August 11, 2023 13:45
Show Gist options
  • Save eneajaho/a6581038608ac0feaf623ef942015333 to your computer and use it in GitHub Desktop.
Save eneajaho/a6581038608ac0feaf623ef942015333 to your computer and use it in GitHub Desktop.
Inject Destroy
import { DestroyRef, inject } from '@angular/core';
import { ReplaySubject } from 'rxjs';
/**
* Injects the `DestroyRef` service and returns a `ReplaySubject` that emits
* when the component is destroyed.
*
* @throws {Error} If no `DestroyRef` is found.
* @returns {ReplaySubject<void>} A `ReplaySubject` that emits when the component is destroyed.
*
* @example
* // In your component:
* export class MyComponent {
* private destroy$ = injectDestroy();
*
* getData() {
* return this.service.getData()
* .pipe(takeUntil(this.destroy$))
* .subscribe(data => { ... });
* }
* }
*/
export const injectDestroy = () => {
const destroyRef = inject(DestroyRef, { optional: true });
if (!destroyRef) throw new Error('No DestroyRef found');
const subject$ = new ReplaySubject<void>(1);
destroyRef.onDestroy(() => {
subject$.next();
subject$.complete();
});
return subject$;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment