Posts

Showing posts from September, 2020

Logging observable accessors

Let’s say you’ve moving observables around in a service.

get somethingCount$() {
    return this.otherService.somethingCount$;
  }

You want to log the result passed forwards, and you hate writing the tap operator.

Usage & Decorator

It would look a lot cleaner and a lot more verbose (in a good way) with a decorator!

@logObservable
get somethingCount$() {
    return this.otherService.somethingCount$;
  }

Here’s the decorator:

import { tap } from 'rxjs/operators';

export const logObservable = (
  target,
  propertyKey: string,
  descriptor: PropertyDescriptor,
) => {
  const orig = descriptor.get;
  descriptor.get = function () {
    return orig.call(this).pipe(
      tap(val => {
          console.log(`[${propertyKey}]`, val);
        }
      )
    );
  };
};

NOTE: Always use function () { for the getter accessor if you want to change the decorator.

if using orig.call(target) in Angular, this.otherService in this example returns undefined.

NGRX Effects - Waiting for other actions

You have A and B as features in NGRX.

A actions:

  • loadA
  • loadASuccess
  • loadAFailure

B actions:

  • loadB
  • loadBSuccess
  • loadBFailure

You want feature C (with loadC / loadCSuccess / loadCFailure) to:

  • Emit its success after making sure that A and B did not fail.
  • Aggregate loadASuccess and loadBSuccess with another observable.

Here’s the switchMap for C’s Effect:

switchMap(action => {
  // load A
  this.store.dispatch(loadA);
  const a$ = this.actions$.pipe(
    ofType(loadASuccess), // filter on loadASuccess
    takeUntil(this.actions$.pipe(ofType(loadAFailure))), // complete without emitting on loadAFailure
    first(), // emit error if completed without an emit, otherwise complete after first emit.
  );
       
  // load B
  this.store.dispatch(loadB);
  const b$ = this.actions$.pipe(
    ofType(loadBSuccess), // filter on loadBSuccess
    takeUntil(this.actions$.pipe(ofType(loadBFailure))),// complete without emitting on loadBFailure
    first(), // emit error if completed without an emit, otherwise complete after first emit.
  );

  // wait for both a$ and b$ to complete. if any fails, error is thrown to pipe.
  return forkJoin({
    a: a$,
    b: b$,
  }).pipe(
    first(), // take(1) is also ok here.
    map(() => loadCSuccess()), // processing, then returning the event here.
    catchError(error => loadCFailure({ error: error?.error })) // on any error, emit loadCFailure.
  );
})

Remember to catchError inside inner scope of switchMap (as done above), otherwise Effect will not trigger again.

Share Replay

Observable A is combineLatest([B,C]).

Subscribing to it later doesn’t work, as no more events would be raised (combineLatest would wait for B and C to emit).

Use takeUntil(this.done$), shareReplay(1) for A as the last step in the pipe.

this.done$ should be a Subject with ngOnDestroy as the trigger:

  ngOnDestroy(): void {
    this.done$.next(true);
    this.done$.complete();
  }

shareReplay(1) completes only when all sources complete, so you’ll have a memory leak (thanks ngrx).