I frequently find my self adding the same sequence of operators to observables, e.g.
observable$
.do(x => console.log(\'some text\', x))
.publishRepla
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));