Created
August 11, 2023 13:45
-
-
Save eneajaho/a6581038608ac0feaf623ef942015333 to your computer and use it in GitHub Desktop.
Inject Destroy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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