Search code examples
angulartypescriptrxjsextension-methods

rxjs pipe tap/map is not triggered when subscribe


I don't know why but when I use Observable with extension method and pipe, the pipe map or tap is not triggering.

import { Observable, Subscriber, Observer } from 'rxjs';
import { tap, map } from 'rxjs/operators';
...
declare module 'rxjs' {
    interface Observable<T> {
        useCache<T>(this: Observable<T>, key: string): Observable<T>;
    }
}
Observable.prototype.useCache = function<T>(this: Observable<T>, key: string) {
    // executed
    const inCache = LocalStorage.get(key);
    if (inCache) {
        return new Observable<T>(observer => observer.next(inCache));
    }
    // this.pipe(tap((e: T) => {
    //     LocalStorage.set(key, e);
    // }));

    this.pipe(map((e: T) => {
        //not executed
        LocalStorage.set(key, e);
    }));
    return this;
};
...
(in somewhere component)
this.service.get(...).subscribe(e=>{
    //executed!
});

In everywhere else, I can set breakpoints that stop there but not inside the map lambda function


Solution

  • The this object isn't being modified. Try returning this with the pipe attached. And because you're not mapping, you can just use a tap.

    Observable.prototype.useCache = function<T>(this: Observable<T>, key: string) {
      const inCache = LocalStorage.get(key);
      if (inCache) {
        return of(inCache);
      }
      return this.pipe(
        tap((e: T) => LocalStorage.set(key, e))
      );
    };