Combine RxJS operators into new operator using TypeScript

前端 未结 2 1705
刺人心
刺人心 2020-12-30 08:18

I frequently find my self adding the same sequence of operators to observables, e.g.

observable$
  .do(x => console.log(\'some text\', x))
  .publishRepla         


        
2条回答
  •  离开以前
    2020-12-30 08:34

    To implement the operator you have described, create a cache.ts file with the following content:

    import { Observable } from "rxjs/Observable";
    import "rxjs/add/operator/do";
    import "rxjs/add/operator/publishReplay";
    
    // Compose the operator:
    
    function cache(this: Observable, text: string): Observable {
      return this
        .do(x => console.log(text, x))
        .publishReplay()
        .refCount();
    }
    
    // Add the operator to the Observable prototype:
    
    Observable.prototype.cache = cache;
    
    // Extend the TypeScript interface for Observable to include the operator:
    
    declare module "rxjs/Observable" {
      interface Observable {
        cache: typeof cache;
      }
    }
    

    And consume it like this:

    import { Observable } from "rxjs/Observable";
    import "rxjs/add/observable/of";
    import "./cache";
    
    let cached = Observable.of(1).cache("some text");
    cached.subscribe(x => console.log(x));
    

提交回复
热议问题