common-ui/src/lib/utils/context.component.ts
2022-07-23 11:33:58 +02:00

18 lines
782 B
TypeScript

import { combineLatest, Observable, of } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { ValuesOf } from './types/utility-types';
export class ContextComponent<T> {
componentContext$: Observable<T> | null = of({} as T);
protected _initContext(context: Record<string, Observable<ValuesOf<T>>>): void {
const observables = Object.values(context).map(obs => obs.pipe(startWith(null)));
const keys = Object.keys(context);
this.componentContext$ = combineLatest(observables).pipe(map(values => this._mapKeysToObs(keys, values)));
}
protected _mapKeysToObs(keys: string[], observables: (ValuesOf<T> | null)[]): T {
return keys.reduce((acc, key, index) => ({ ...acc, [key]: observables[index] }), {} as T);
}
}