Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 226047b

Browse files
committed
feat(state): introduce rxEffects creation function
1 parent 1d011aa commit 226047b

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

libs/state/effects/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
export { RxEffects } from './lib/effects.service';
2+
export { rxEffects } from './lib/effects';

libs/state/effects/src/lib/effects.ts

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)