All files / json-crdt-repo/src/util/rx shareByKey.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 4/4
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1814x   14x 117x 117x 88x 88x 72x   72x                
import {defer, finalize, type Observable, share} from 'rxjs';
 
export const shareByKey = <TValue>(sub: (key: string) => Observable<TValue>): ((key: string) => Observable<TValue>) => {
  const map: Record<string, Observable<TValue>> = {};
  return (key: string) => {
    const observable = map[key];
    if (observable) return observable;
    return (map[key] = defer(() => sub(key)).pipe(
      finalize(() => {
        delete map[key];
      }),
      share({
        resetOnRefCountZero: true,
      }),
    ));
  };
};