title: RxJS: Observable stream piped to groupBy() followed by concatMap(); data for subsequent keys lost
body: <p>I am trying to use the RxJS <code>groupBy</code> operator followed by <code>concatMap</code> to collect records into individual groups based on some keys.</p>
  
  <p>I have noticed that when <code>concatMap</code> follows a <code>groupBy</code> operator, it seems to lose the data for all the keys that occur after the first one.</p>
  
  <p>For Example:</p>
  
  <p>Consider the following code block:</p>
  
  <pre><code>// DOES NOT WORK
  const records = ['a:1', 'b:2', 'c:3', 'd:1', 'e:2', 'f:3', 'g:1'];
  const clicks = new Subject();
  
  const result = clicks.pipe(
    groupBy(x =&gt; x.substr(2,1)),
    concatMap(ev$ =&gt; ev$.pipe(map(x =&gt; ({key: ev$.key, value: x})))),
  );
  const subscription = result.subscribe(x =&gt; console.log(x));
  
  records.forEach(x =&gt; clicks.next(x));
  
  // Expected Output:
  // { key: '1', value: 'a:1' }
  // { key: '1', value: 'd:1' }
  // { key: '1', value: 'g:1' }
  // { key: '2', value: 'b:2' }
  // { key: '2', value: 'e:2' }
  // { key: '3', value: 'c:3' }
  // { key: '3', value: 'f:3' }
  // 
  // Actual Output:
  // { key: '1', value: 'a:1' }
  // { key: '1', value: 'd:1' }
  // { key: '1', value: 'g:1' }
  // ...Nothing more -- no results for key 2 and 3
  </code></pre>
  
  <p>However, when I use the <code>concatMap</code> operator on its own, it behaves as expected.</p>
  
  <pre><code>// WORKS
  const records = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  const clicks = new Subject();
  
  const result = clicks.pipe(
    concatMap(ev =&gt; ev.subject$.pipe(take(4), map(x =&gt; ev.key + x))),
  );
  const subscription = result.subscribe(x =&gt; console.log(x));
  
  records.forEach(x =&gt; clicks.next({key: x, subject$: interval(1000)}));
  
  // Expected &amp; Actual Output:
  // a0
  // a1
  // a2
  // a3
  // b0
  // b1
  // b2
  // b3
  // c0
  // c1
  // c2
  // c3
  // d0
  // d1
  // d2
  // d3
  // e0
  // e1
  // e2
  // e3
  // f0
  // f1
  // f2
  // f3
  // g0
  // g1
  // g2
  // g3
  </code></pre>
  
  <p>Reading through the documentation for RxJS <a href="https://rxjs-dev.firebaseapp.com/api/operators/groupBy" rel="noreferrer"><code>groupBy</code></a> and <a href="https://rxjs-dev.firebaseapp.com/api/operators/concatMap" rel="noreferrer"><code>concatMap</code></a> does not provide me with any clues as to what could be going on here. Whereas the section on RxJS <code>concatMap</code> at <a href="http://reactivex.io/documentation/operators/flatmap.html" rel="noreferrer">reactivex.io</a> leads me to believe that this should work.</p>
  
  <p>Can anyone help me understand what's going on with the first scenario here? How can I get the first scenario to work?</p>