title: RxJS: Backpressure with switchMap producing N values
body: <p>I am talking to some RESTful search endpoint that involves pagination. The query is triggered by user typing in a search field, and as a result it produces an Observable with N values, corresponding to the N result pages.</p>
  
  <p>The code looks somewhat like the following:</p>
  
  <pre><code>function runQueries(queryObservable) {
    return queryObservable
             .debounceTime(500)
             .distinctUntilChanged()
             .switchMap(search);
  }
  
  function search(query) {
    return Observable.create(observer =&gt; searchInto(observer, query, 0));
  }
  
  function searchInto(observer, query, start) {
    runQuery(query, start).subscribe(result =&gt; {
      observer.next(result);
      if (hasMorePages(result)) {
        searchInto(observer, query, start + 1);
      } else {
        observer.complete();
      }
    });
  }
  </code></pre>
  
  <p>Now, the search requests can take a while and I don't want to retrieve all the pages if user changes the query.</p>
  
  <p>Let's say the search return 3 pages, and user changes the query after one page is loaded. I want to see something like:</p>
  
  <pre><code>USER: types query A
  CODE: loads page A1
  USER: types query B
  CODE: loads page B1
  CODE: loads page B2
  CODE: loads page B3
  </code></pre>
  
  <p><code>switchMap</code> gets half of the job done. The resulting observable has the correct sequence: A1, B1, B2, B3. Great.</p>
  
  <p>However, behind the scenes my recursive search is still running all the queries, putting unnecessary load on the server, network, etc. <code>switchMap</code> does discard the "obsolete" results, but it does not prevent the recursive function from doing its work to the end. In other words, it looks like:</p>
  
  <pre><code>USER: types query A
  CODE: loads page A1   -&gt; returned by search observable
  USER: types query B
  CODE: loads page A2   -&gt; discarded by search observable
  CODE: loads page B1   -&gt; returned by search observable
  CODE: loads page B2   -&gt; returned by search observable
  CODE: loads page A3   -&gt; discarded by search observable
  CODE: loads page B3   -&gt; returned by search observable
  </code></pre>
  
  <p>The sequence of "A" and "B" is random (subject to race conditions), but it doesn't matter.</p>
  
  <p>What am I doing wrong? What is the idiomatic solution to this?</p>