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

Skip to content

feat(state): allow to pass injector to rxState and rxEffects #1840

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions apps/docs/docs/state/effects/effects.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,7 @@ export class EffectsService {
readonly effects = rxEffects();

// share only some APIs if you like
register: typeof this.effects.register = this.effects.register.bind(
this.effects
);
register: typeof this.effects.register = this.effects.register.bind(this.effects);
}
```

Expand Down Expand Up @@ -347,32 +345,28 @@ class MyComponent {
readonly effects = rxEffects(({ register }) => {
register(
this.login$.pipe(
exhaustMap(({ user, pass }) =>
this.http.post('/auth/', { user, pass })
),
exhaustMap(({ user, pass }) => this.http.post('/auth/', { user, pass })),
// retry when an error occurs
retry()
retry(),
),
(data) => {
alert(`welcome ${data.user}`);
}
},
);

register(
this.login$.pipe(
exhaustMap(({ user, pass }) =>
this.http.post('/auth/', { user, pass })
),
exhaustMap(({ user, pass }) => this.http.post('/auth/', { user, pass })),
// catch the error and return a custom value
catchError((err) => {
return of(null);
})
}),
),
(data) => {
if (data) {
alert(`welcome ${data.user}`);
}
}
},
);
});
}
Expand All @@ -391,14 +385,10 @@ export class ChartComponent {
chartVisible$ = new Subject<boolean>();
chartData$ = this.ngRxStore.select(getListData());

pollingTrigger$ = this.chartVisible$.pipe(
switchMap((isPolling) => (isPolling ? interval(2000) : EMPTY))
);
pollingTrigger$ = this.chartVisible$.pipe(switchMap((isPolling) => (isPolling ? interval(2000) : EMPTY)));

readonly effects = rxEffects(({ register }) => {
register(this.pollingTrigger$, () =>
this.ngRxStore.dispatch(refreshAction())
);
register(this.pollingTrigger$, () => this.ngRxStore.dispatch(refreshAction()));
});
}
```
Expand Down Expand Up @@ -654,6 +644,12 @@ The `untilEffect` top level API was dropped. You would need to build your own wo

:::

### Injection context

`rxEffects` must be initialized in an [injection context](https://angular.dev/guide/di/dependency-injection-context).

If you want to initialize `rxEffects` outside of an injection context you can pass an `injector` via the `options` parameter.

## Testing

The `rxEffects` API is designed to not force developers to interact with its instance in order to properly test your
Expand Down
6 changes: 6 additions & 0 deletions apps/docs/docs/state/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -795,3 +795,9 @@ Not support anymore, please choose either the RxState as a Service approach, or
</Tabs>

_Disclaimer_: this doc is work in progress. Not every use case has found its way into the docs. We encourage you to contribute 🙂.

### Injection context

`rxState` must be initialized in an [injection context](https://angular.dev/guide/di/dependency-injection-context).

If you want to initialize `rxState` outside of an injection context you can pass an `injector` via the `options` parameter.
29 changes: 28 additions & 1 deletion libs/state/effects/src/lib/rx-effects.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component } from '@angular/core';
import { Component, EnvironmentInjector } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { jestMatcher } from '@test-helpers/rx-angular';
import { Observable, of, Subject, tap, timer } from 'rxjs';
Expand Down Expand Up @@ -104,6 +104,24 @@ describe(rxEffects, () => {
expect(spyInternalOnCleanup).toHaveBeenCalled();
expect(spyOnCleanup).toHaveBeenCalled();
});

describe('without injection context', () => {
it('should throw when invoked without injection context', () => {
const { rxEffects } = setUpWithoutInjectionContext();
expect(() => rxEffects(() => {}, {})).toThrow(
/rxEffects\(\) can only be used within an injection context/,
);
});

it('should be able to use a custom Injector', () => {
const { rxEffects } = setUpWithoutInjectionContext();

const envInjector = TestBed.inject(EnvironmentInjector);

const effects = rxEffects(() => {}, { injector: envInjector });
expect(effects).toBeDefined();
});
});
});

function setupComponent(setupFn?: RxEffectsSetupFn) {
Expand All @@ -123,3 +141,12 @@ function setupComponent(setupFn?: RxEffectsSetupFn) {
component: fixture.componentInstance,
};
}

function setUpWithoutInjectionContext() {
return {
rxEffects(...args: Parameters<typeof rxEffects>) {
const effects = rxEffects(...args);
return effects;
},
};
}
192 changes: 116 additions & 76 deletions libs/state/effects/src/lib/rx-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,43 @@ import {
DestroyRef,
ErrorHandler,
inject,
Injector,
runInInjectionContext,
} from '@angular/core';
import { from, Subscription } from 'rxjs';
import { SideEffectFnOrObserver, SideEffectObservable } from './types';

interface RxEffects {
register<T>(
observable: SideEffectObservable<T>,
sideEffectOrObserver?: SideEffectFnOrObserver<T>
sideEffectOrObserver?: SideEffectFnOrObserver<T>,
): Fn;
onDestroy: (fn: Fn) => Fn;
}

type Fn = () => void;

export type RxEffectsSetupFn = (
cfg: Pick<RxEffects, 'register' | 'onDestroy'>
cfg: Pick<RxEffects, 'register' | 'onDestroy'>,
) => void;

export type RxEffectsOptions = {
injector?: Injector;
};

function getInjectorFromOptions<
SetupFn extends Function,
Options extends { injector?: Injector },
>(setupFnOrOptions?: SetupFn | Options, options?: Options) {
if (options?.injector) {
return options.injector;
}
if (setupFnOrOptions && typeof setupFnOrOptions !== 'function') {
return setupFnOrOptions.injector;
}
return undefined;
}

/**
* @description
* Functional way to setup observable based side effects with RxEffects.
Expand Down Expand Up @@ -55,83 +74,104 @@ export type RxEffectsSetupFn = (
* @docsPage RxEffects
*
*/
export function rxEffects(setupFn?: RxEffectsSetupFn): RxEffects {
assertInInjectionContext(rxEffects);
const errorHandler = inject(ErrorHandler, { optional: true });
const destroyRef = inject(DestroyRef);
const runningEffects: Subscription[] = [];
destroyRef.onDestroy(() => runningEffects.forEach((ef) => ef.unsubscribe()));

/**
* Subscribe to observables and trigger side effect.
*
* @example
*
* /@Component({
* template: `<button name="save" (click)="save()">Save</button>`
* })
* class ListComponent {
* private ef = rxEffects(({register}) => {
* register(timer(0, this.backupInterval), console.log));
* }
* }
*
* @param {SideEffectObservable} obs$ Source observable input
* @param {SideEffectFnOrObserver} sideEffect Observer object
*
* @return {Function} - unregisterFn
*/
function register<T>(
obs$: SideEffectObservable<T>,
sideEffect?: SideEffectFnOrObserver<T>
): () => void {
const observer =
typeof sideEffect === 'object'
? {
...sideEffect,
// preserve original logic
error: (e: unknown) => {
sideEffect.error?.(e);
errorHandler?.handleError(e);
},
}
: {
next: sideEffect,
error: (e: unknown) => errorHandler?.handleError(e),
};
const sub = from(obs$).subscribe(observer);
runningEffects.push(sub);
return () => sub.unsubscribe();
export function rxEffects(): RxEffects;
export function rxEffects(setupFn: RxEffectsSetupFn): RxEffects;
export function rxEffects(options: RxEffectsOptions): RxEffects;
export function rxEffects(
setupFn: RxEffectsSetupFn,
options: RxEffectsOptions,
): RxEffects;
export function rxEffects(
setupFnOrOptions?: RxEffectsSetupFn | RxEffectsOptions,
options?: RxEffectsOptions,
): RxEffects {
const injectorFromOptions = getInjectorFromOptions(setupFnOrOptions, options);
if (!injectorFromOptions) {
assertInInjectionContext(rxEffects);
}

/**
* Register custom cleanup logic.
*
* @example
*
* /@Component({
* template: `<button name="save" (click)="save()">Save</button>`
* })
* class ListComponent {
* private ef = rxEffects(({onDestroy}) => {
* onDestroy(() => console.log('done'));
* }
* }
*
* @param {Fn} callback onDestroy callback
*
* @return {Fn} unregisterFn
*/
function onDestroy(callback: Fn): Fn {
return destroyRef.onDestroy(callback);
}
const injector = injectorFromOptions ?? inject(Injector);

return runInInjectionContext(injector, () => {
const errorHandler = inject(ErrorHandler, { optional: true });
const destroyRef = inject(DestroyRef);
const runningEffects: Subscription[] = [];
destroyRef.onDestroy(() =>
runningEffects.forEach((ef) => ef.unsubscribe()),
);

/**
* Subscribe to observables and trigger side effect.
*
* @example
*
* /@Component({
* template: `<button name="save" (click)="save()">Save</button>`
* })
* class ListComponent {
* private ef = rxEffects(({register}) => {
* register(timer(0, this.backupInterval), console.log));
* }
* }
*
* @param {SideEffectObservable} obs$ Source observable input
* @param {SideEffectFnOrObserver} sideEffect Observer object
*
* @return {Function} - unregisterFn
*/
function register<T>(
obs$: SideEffectObservable<T>,
sideEffect?: SideEffectFnOrObserver<T>,
): () => void {
const observer =
typeof sideEffect === 'object'
? {
...sideEffect,
// preserve original logic
error: (e: unknown) => {
sideEffect.error?.(e);
errorHandler?.handleError(e);
},
}
: {
next: sideEffect,
error: (e: unknown) => errorHandler?.handleError(e),
};
const sub = from(obs$).subscribe(observer);
runningEffects.push(sub);
return () => sub.unsubscribe();
}

const effects = {
register,
onDestroy,
};
/**
* Register custom cleanup logic.
*
* @example
*
* /@Component({
* template: `<button name="save" (click)="save()">Save</button>`
* })
* class ListComponent {
* private ef = rxEffects(({onDestroy}) => {
* onDestroy(() => console.log('done'));
* }
* }
*
* @param {Fn} callback onDestroy callback
*
* @return {Fn} unregisterFn
*/
function onDestroy(callback: Fn): Fn {
return destroyRef.onDestroy(callback);
}

setupFn?.(effects);
const effects = {
register,
onDestroy,
};
if (setupFnOrOptions && typeof setupFnOrOptions === 'function') {
setupFnOrOptions(effects);
}

return effects;
return effects;
});
}
Loading
Loading