title: Wait for a promise to resolve with RxJs
body: <p>I'm trying to implement a "save on type" feature for a form using <a href="https://github.com/ReactiveX/rxjs" rel="noreferrer">RxJS v5 beta</a>.</p>
  
  <p>The data should be posted to the backend as the user types into the text fields. I'm creating a <code>Rx.Subject</code> to fire new events (<code>next()</code>) for new user input and post it with HTTP requests.</p>
  
  <p>I've used this question as a starting point: <a href="https://stackoverflow.com/questions/37173877/rxjs-wait-until-promise-resolved">RxJS wait until promise resolved</a></p>
  
  <p>However, with the solution from this post, simultaneous request to the backend are sent. </p>
  
  <p>My goal is to only send one request and defer following requests until a running request has completed. After completion of the request the last of the pending events should be emitted (like it is the case in <code>debounceTime</code>)</p>
  
  <p>The <code>example</code> function in the following snippet uses the approach from the linked SO question. This sends requests for all the input values.</p>
  
  <p>The <code>workaround</code> function function uses a promise stored outside of the "stream" to block and wait for a previous request. This works and only sends a request for the last input value. But that seems to not follow the concept of RxJs and feels hacky.</p>
  
  <p>Is there a way to achieve this with RxJS?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function fakeRequest(value) {
    console.log('start request:', value)
    return new Promise((resolve) =&gt; { 
      setTimeout(() =&gt; resolve(value), 1000);
   });
  }
  
  function example() {
    let subject = new Rx.Subject();
    
    subject
      .debounceTime(500)
      .switchMap(input =&gt; fakeRequest(input))
      .subscribe(data =&gt; console.log(data))
  
    subject.next('example value 1');
    subject.next('example value 2');
    subject.next('example value 3');
    subject.next('example value 4');
  }
  
  
  function workaround() {
    let subject = new Rx.Subject();
  
    let p = Promise.resolve();
    subject
      .debounceTime(500)  
      .switchMap(input =&gt; p.then(() =&gt; input))
      .do(input =&gt; p = fakeRequest(input))
      .subscribe(data =&gt; console.log(data))
  
    subject.next('workaround value 1');
    subject.next('workaround value 2');
    subject.next('workaround value 3');
    subject.next('workaround value 4');
  }
  
  example();
  // workaround();</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/@reactivex/rxjs@5.0.0-rc.2/dist/global/Rx.js"&gt;&lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>