I frequently find my self adding the same sequence of operators to observables, e.g.
observable$
.do(x => console.log('some text', x))
.publishReplay()
.refCount();
I'm looking for a way to combine these 3 operators in a small reusable operator (e.g. .cache('some text')
) that I can chain to any observable. How can I define this in Typescript, so that I could import rxjs/Observable and this operator, like I do with rxjs operators?
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<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;
}
}
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));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments