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

Skip to content

WIP Rx state/connect partial obs and signals #1644

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { isPartialOfSignalsOrObservablesGuard } from '@rx-angular/state/selections';
import { of } from 'rxjs';
import { signal } from '@angular/core';

describe('isPartialOfSignalsOrObservablesGuard', () => {
it('should return false if arg is no object', () => {
expect(isPartialOfSignalsOrObservablesGuard('some')).toEqual(false);
});
it('should return true if all props are either observables or signals', () => {
expect(
isPartialOfSignalsOrObservablesGuard({
a: of(true),
b: signal(10),
})
).toEqual(true);
});
it('should return false if one prop is neither a observable or signal', () => {
expect(
isPartialOfSignalsOrObservablesGuard({
a: of(true),
b: signal(10),
c: true,
})
).toEqual(false);
});
});
1 change: 1 addition & 0 deletions libs/state/selections/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export {
isStringAndFunctionTupleGuard,
isStringArrayFunctionAndOptionalObjectTupleGuard,
isStringArrayGuard,
isPartialOfSignalsOrObservablesGuard,
} from './lib/utils/guards';
export { pipeFromArray } from './lib/utils/pipe-from-array';
export { safePluck } from './lib/utils/safe-pluck';
22 changes: 21 additions & 1 deletion libs/state/selections/src/lib/utils/guards.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { OperatorFunction } from 'rxjs';
import { Observable, OperatorFunction, isObservable } from 'rxjs';
import { isSignal, Signal } from '@angular/core';

export function isPromiseGuard<T>(value: unknown): value is Promise<T> {
return (
Expand Down Expand Up @@ -69,3 +70,22 @@ export function isStringArrayFunctionAndOptionalObjectTupleGuard<R>(
(op[2] === undefined || typeof op[2] === 'object')
);
}

export function isPartialOfSignalsOrObservablesGuard<T, K extends keyof T>(
arg: unknown
): arg is Partial<{ [K: string]: Observable<T[K]> | Signal<T[K]> }> {
if (!isObjectGuard(arg)) {
return false;
}
for (const key in arg) {
// eslint-disable-next-line no-prototype-builtins
if (arg.hasOwnProperty(key)) {
// @ts-ignore
if (!isObservable(arg[key]) && !isSignal(arg[key])) {
return false;
}
}
}

return true;
}
28 changes: 28 additions & 0 deletions libs/state/spec/convert-partials-to.observable.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { convertPartialsToObservable } from '../src/lib/convert-partials-to.observable';
import { EMPTY, NEVER, of } from 'rxjs';
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';

describe('convertPartialsToObservable', () => {
it('should emit once initially and combine all partials', (done) => {
TestBed.runInInjectionContext(() => {
const result = convertPartialsToObservable<TestModel, keyof TestModel>({
a: of('Hi'),
b: signal(10),
// c: NEVER,
// d: EMPTY
});

result.subscribe((value) => {
expect(value).toEqual({ a: 'Hi', b: 10, c: undefined, d: undefined });
done();
});
});
});
});
interface TestModel {
a: string;
b: number;
c: boolean;
d: string;
}
25 changes: 24 additions & 1 deletion libs/state/spec/rx-state.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injector, runInInjectionContext } from '@angular/core';
import { Injector, runInInjectionContext, signal } from '@angular/core';
import { fakeAsync, TestBed } from '@angular/core/testing';
import { RxState } from '../src/lib/rx-state.service';
import { select } from '@rx-angular/state/selections';
Expand Down Expand Up @@ -493,6 +493,29 @@ describe('RxStateService', () => {
});
});

it('should connect partial of observables and signals', () => {
testScheduler.run(({ expectObservable }) => {
const s: { num: number; b: boolean } = { num: 5, b: false };
const state = setupState({ initialState: s });
const b = signal(true);

expectObservable(state.$.pipe(map((st) => st))).toBe('(abc)', {
a: undefined,
b: 43,
c: undefined,
});

state.connect({
num: scheduled(
[{ num: undefined }, { num: 43 }, { num: undefined }],
testScheduler
),
b,
});
b.set(false);
});
});

it('should throw with wrong params', () => {
const state = setupState({ initialState: initialPrimitiveState });

Expand Down
40 changes: 40 additions & 0 deletions libs/state/src/lib/convert-partials-to-observable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { combineLatest, from, isObservable, Observable, startWith } from 'rxjs';
import { Injector, isSignal, Signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { map } from 'rxjs/operators';
import { coalesceWith } from '@rx-angular/cdk/coalescing';
import { Promise } from '@rx-angular/cdk/zone-less/browser';

export function convertPartialsToObservable<
T extends object,
K extends keyof T
>(
input: Partial<{ [K: string]: Observable<T[K]> | Signal<T[K]> }>,
injector?: Injector
): Observable<Partial<T>> {
const keys = Object.keys(input);

const observables = keys.map((key) => {
const obsOrSignal = input[key];

if (isObservable(obsOrSignal)) {
return obsOrSignal?.pipe(startWith(undefined));
}
if (isSignal(obsOrSignal)) {
return toObservable(obsOrSignal, { injector });
}

throw new TypeError(`Expected type Observable or Signal for key "${key}"`);
});

return combineLatest(observables).pipe(
coalesceWith(from(Promise.resolve())),
map((values) => {
const result: Partial<T> = {} as Partial<T>;
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
})
);
}
23 changes: 22 additions & 1 deletion libs/state/src/lib/rx-state.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
createAccumulationObservable,
createSideEffectObservable,
isKeyOf,
isPartialOfSignalsOrObservablesGuard,
KeyCompareMap,
PickSlice,
safePluck,
Expand All @@ -29,6 +30,7 @@ import {
} from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { createSignalStateProxy, SignalStateProxy } from './signal-state-proxy';
import { convertPartialsToObservable } from './convert-partials-to-observable';

export type ProjectStateFn<T> = (oldState: T) => Partial<T>;
export type ProjectValueFn<T, K extends keyof T> = (oldState: T) => T[K];
Expand Down Expand Up @@ -315,6 +317,13 @@ export class RxState<T extends object> implements OnDestroy, Subscribable<T> {
* Any change emitted by the source will get merged into the state.
*/
connect(signal: Signal<Partial<T>>): void;
/**
* @description
* Connect a Partial of `Signals` or `Observables` to the state `T`.
*/
connect<K extends keyof T>(
partial: Partial<{ [K: string]: Observable<T[K]> | Signal<T[K]> }>
): void;

/**
* @description
Expand Down Expand Up @@ -402,7 +411,8 @@ export class RxState<T extends object> implements OnDestroy, Subscribable<T> {
projectOrSlices$?:
| ProjectStateReducer<T, V>
| Observable<T[K] | V>
| Signal<T[K] | V>,
| Signal<T[K] | V>
| Partial<{ [K: string]: Observable<T[K]> | Signal<T[K]> }>,
projectValueFn?: ProjectValueReducer<T, K, V>
): void {
/**
Expand All @@ -424,6 +434,17 @@ export class RxState<T extends object> implements OnDestroy, Subscribable<T> {
return;
}

if (
isPartialOfSignalsOrObservablesGuard(keyOrInputOrSlice$) &&
!projectOrSlices$ &&
!projectValueFn
) {
this.accumulator.nextSliceObservable(
convertPartialsToObservable(keyOrInputOrSlice$, this.injector)
);
return;
}

if (
isObservable(keyOrInputOrSlice$) &&
projectOrSlices$ &&
Expand Down