I need to cache the result of a request on the first call then read the cached value for subsequent calls.
To achieve that goal, I am using promises and I am chaining them. I have a working solution but I would like to convert it to RxJS's observables instead of Promises.
Here is my working solution:
private currentPromise: Promise<{ [key: string]: any }>;
private cache: any;
public getSomething(name: string): Promise<number>{
return this.currentPromise = !this.currentPromise ?
this._getSomething(name) :
new Promise((r) => this.currentPromise.then(() => this._getSomething(name).then((res) => r(res))));
}
private _getSomething(name: string): Promise<any> {
return new Promise((resolve) => {
if (this.cache[name]) {
this.messages.push("Resolved from cache");
resolve(this.cache[name]);
} else {
// Fake http call. I would use Angular's Http class.
setTimeout(()=> {this.messages.push("Resolved from server"); this.cache[name] = name; resolve(this.cache[name]); }, 2000 );
}
});
}
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
this.getSomething("thing1").then((res)=>this.messages.push(res));
this.getSomething("thing2").then((res)=>this.messages.push(res));
You can test it on this plunkr: https://plnkr.co/edit/j1pm2GeQf6oZwRvbUsXJ?p=preview
How do I achieve the same thing with RxJS 5 beta?
Update
Following Bergi's comments I updated my plunkr and my code to bring it closer to my real case