All files / app/operators ifFirst.ts

100% Statements 12/12
100% Branches 3/3
100% Functions 4/4
100% Lines 12/12

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 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                          1x 866x 862x   866x 866x 866x     806x 786x 677x       16x 8x 8x              
import { Observable, tap } from 'rxjs';
 
/**
 * Operator that will run some predicate only for the first emission, once
 * across all subscribers.
 *
 * @param predicateNext The predicate to run if the first emission is successful
 * @param predicateError The predicate to run if the first emission is an error.
 *   If none specified, the one used when the first emission is successful will
 *   be used
 * @returns The operator
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const ifFirst = (predicateNext: any, predicateError?: any) => {
  if (predicateError === undefined) {
    predicateError = predicateNext;
  }
  let first = true;
  return <T>(source: Observable<T>) => {
    return source.pipe(
      tap({
        next: (v) => {
          if (first) {
            predicateNext(v);
            first = false;
          }
        },
        error: (e) => {
          if (first) {
            predicateError(e);
            first = false;
          }
        },
      })
    );
  };
};