使用TypeScript将RxJS运算符组合到新运算符中

Pet*_*ert 11 rxjs typescript rxjs5

我经常发现自己将相同的运算符序列添加到可观察量中,例如

observable$
  .do(x => console.log('some text', x))
  .publishReplay()
  .refCount();
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来将这3个运算符组合在一个小的可重用运算符(例如.cache('some text'))中,我可以链接到任何可观察的运算符.我如何在Typescript中定义它,以便我可以导入rxjs/Observable和这个运算符,就像我使用rxjs运算符一样?

car*_*ant 22

要实现您所描述的运算符,请cache.ts使用以下内容创建一个文件:

import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
import "rxjs/add/operator/publishReplay";

// Compose the operator:

function cache<T>(this: Observable<T>, text: string): Observable<T> {
  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<T> {
    cache: typeof cache;
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样消耗它:

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));
Run Code Online (Sandbox Code Playgroud)