All files / src/app/store/selector-helpers selector-helpers.ts

100% Statements 50/50
100% Branches 32/32
100% Functions 18/18
100% Lines 37/37
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 771x 1x 1x 1x   15x 8x 7x     4x 2x       39x 20x   18x   9x 2x       82x 44x 44x         12x 13x     1x 10x 10x     19x 12x 12x 12x     12x 12x       12x     5x 3x 3x     1x 1x 1x 1x 1x                        
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/toArray';
 
export function waitforFirstNotNull<T>(selector$: Observable<T>, fnOnData, fnOnError = null) {
  selector$
    .filter(data => !!data)
    .take(1)
    .subscribe(
      (data) => { fnOnData(data); },
      (error) => { console.error(error); if (fnOnError) { fnOnError(error); } }
    );
}
 
export function ifNull<T>(selector$: Observable<T>, fnWhenNoData, fnOnError = null) {
  selector$
    .take(1)
    .filter(data => data === null || data === undefined)
    .subscribe(
      (falsyData) => { fnWhenNoData(falsyData); },
      (error) => { console.error(error); if (fnOnError) { fnOnError(error); } }
    );
}
 
export const waitFor$ = function(fn = null) {
  fn = fn || (data => !!data);
  return this
    .filter(fn)
    .take(1);
};
 
export const waitForWithCondition$ = function(predicate = null) {
  return this.filter(data => !!data && (!!predicate ? predicate(data) : true ) ).take(1);
};
 
export const ifNull$ = function() {
  return this.take(1)
    .filter(data => data === null || data === undefined);
};
 
export const snapshot = function(transform = null): any[] | any | undefined {
  transform = transform || function(data) { return data; };  // if no fn given, assign a pass-through
  let result = null;
  this
    .toArray()  // gather all values
    .subscribe(data => {
      result = transform(data);
      result = (result.length === 0) ? undefined  // down-grade an empty array to undefined
        : (result.length === 1) ? result[0]       // down-grade a single value array to the single value
        : result;
      });
  return result;
};
 
export const logSnapshot = function(transform = null) {
  console.log('Snapshot: ', this.snapshot(transform));
  return this;
};
 
Observable.prototype.waitFor$ = waitFor$;
Observable.prototype.waitForWithCondition$ = waitForWithCondition$;
Observable.prototype.ifNull$ = ifNull$;
Observable.prototype.snapshot = snapshot;
Observable.prototype.logSnapshot = logSnapshot;
 
declare module 'rxjs/Observable' {
  // tslint:disable-next-line:no-shadowed-variable
  interface Observable<T> {
    waitFor$: typeof waitFor$;
    waitForWithCondition$: typeof waitForWithCondition$;
    ifNull$: typeof ifNull$;
    snapshot: typeof snapshot;
    logSnapshot: typeof logSnapshot;
  }
}