I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interested in transitioning it to RxJS's observables instead of Promises.
Below is the code snippet illustrating 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 {
// Simulated http call. Ideally using 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 experiment with the code on this plunkr link: https://plnkr.co/edit/j1pm2GeQf6oZwRvbUsXJ?p=preview
I am now looking for guidance on how to achieve the same functionality with RxJS 5 beta.
Update
Considering Bergi's feedback, I have updated both my plunkr example and code to align better with my real-world scenario.