|
| 1 | +import { |
| 2 | + DestroyRef, |
| 3 | + assertInInjectionContext, |
| 4 | + inject, |
| 5 | + ErrorHandler, |
| 6 | +} from '@angular/core'; |
| 7 | +import { RxEffects } from './effects.service'; |
| 8 | + |
| 9 | +export type RxEffectsSetupFn = ( |
| 10 | + rxEffect: Pick<RxEffects, 'register' | 'registerOnDestroy'> |
| 11 | +) => void; |
| 12 | + |
| 13 | +/** |
| 14 | + * @description |
| 15 | + * Functional way to setup observable based side effects with RxEffects. |
| 16 | + * It's a creation function for RxEffects that destroys itself when the provided |
| 17 | + * `DestroyRef` is destroyed. |
| 18 | + * |
| 19 | + * @example |
| 20 | + * ```ts |
| 21 | + * import { rxEffects } from '@rx-angular/state/effects'; |
| 22 | + * |
| 23 | + * \@Component({}) |
| 24 | + * export class FooComponent { |
| 25 | + * private readonly util = inject(Util); |
| 26 | + * readonly effects = rxEffects(({ register }) => { |
| 27 | + * register(this.util.windowResize$, () => { |
| 28 | + * console.log('window was resized'); |
| 29 | + * }) |
| 30 | + * }); |
| 31 | + * |
| 32 | + * ngOnInit() { |
| 33 | + * this.effects.register(this.util.rotationChanged$, () => { |
| 34 | + * console.log('viewport rotation changed'); |
| 35 | + * }); |
| 36 | + * } |
| 37 | + * } |
| 38 | + * ``` |
| 39 | + * |
| 40 | + * @param {RxEffectsSetupFn} setupFn |
| 41 | + * @returns RxEffects |
| 42 | + * |
| 43 | + * |
| 44 | + * |
| 45 | + * @docsCategory RxEffects |
| 46 | + * @docsPage RxEffects |
| 47 | + * |
| 48 | + */ |
| 49 | +export function rxEffects(setupFn?: RxEffectsSetupFn): RxEffects { |
| 50 | + assertInInjectionContext(rxEffects); |
| 51 | + const errorHandler = inject(ErrorHandler, { optional: true }); |
| 52 | + const effects = new RxEffects(errorHandler); |
| 53 | + const destroyRef = inject(DestroyRef); |
| 54 | + |
| 55 | + destroyRef.onDestroy(() => effects.ngOnDestroy()); |
| 56 | + |
| 57 | + setupFn?.({ |
| 58 | + register: effects.register.bind(effects), |
| 59 | + registerOnDestroy: effects.registerOnDestroy.bind(effects), |
| 60 | + }); |
| 61 | + |
| 62 | + return effects; |
| 63 | +} |
0 commit comments