title: How to dynamically chain function calls using RXJS?
body: <p>I need to cache the result of a request on the first call then read the cached value for subsequent calls.</p>
  
  <p>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.</p>
  
  <p>Here is my working solution:</p>
  
  <pre><code>private currentPromise: Promise&lt;{ [key: string]: any }&gt;;
  private cache: any;
  public getSomething(name: string): Promise&lt;number&gt;{
    return this.currentPromise = !this.currentPromise ? 
      this._getSomething(name) : 
      new Promise((r) =&gt; this.currentPromise.then(() =&gt; this._getSomething(name).then((res) =&gt; r(res))));
  }
  
  private _getSomething(name: string): Promise&lt;any&gt; {
    return new Promise((resolve) =&gt; {
      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(()=&gt; {this.messages.push("Resolved from server"); this.cache[name] = name; resolve(this.cache[name]); }, 2000 );
        }
    });
  }
  
  this.getSomething("thing1").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing1").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing2").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing2").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing1").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing2").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing1").then((res)=&gt;this.messages.push(res));
  this.getSomething("thing2").then((res)=&gt;this.messages.push(res));
  </code></pre>
  
  <p>You can test it on this plunkr: <a href="https://plnkr.co/edit/j1pm2GeQf6oZwRvbUsXJ?p=preview" rel="nofollow">https://plnkr.co/edit/j1pm2GeQf6oZwRvbUsXJ?p=preview</a></p>
  
  <p>How do I achieve the same thing with RxJS 5 beta?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Following Bergi's comments I updated my plunkr and my code to bring it closer to my real case</p>