title: RxJS: Batch requests and share response
body: <p>Let's imagine i have a function <code>fetchUser</code> which takes as parameter <code>userId</code> and return an <strong>observable of user</strong>. </p>
  
  <p>As i am calling this method often, i want to <strong>batch</strong> the ids to perform one request with multiple ids instead !</p>
  
  <p><em>Here my troubles began...</em> </p>
  
  <p>I can't find a solution to do that without sharing an observable between the different calls of <code>fetchUser</code>.</p>
  
  <pre><code>import { Subject, from } from "rxjs"
  import { bufferTime, mergeMap, map, toArray, filter, take, share } from "rxjs/operators"
  
  const functionThatSimulateAFetch = (userIds: string[]) =&gt; from(userIds).pipe(
      map((userId) =&gt; ({ id: userId, name: "George" })),
      toArray(),
  )
  
  const userToFetch$ = new Subject&lt;string&gt;()
  
  const fetchedUser$ = userToFetch$.pipe(
      bufferTime(1000),
      mergeMap((userIds) =&gt; functionThatSimulateAFetch(userIds)),
      share(),
  )
  
  const fetchUser = (userId: string) =&gt; {
      const observable = fetchedUser$.pipe(
          map((users) =&gt; users.find((user) =&gt; user.id === userId)),
          filter((user) =&gt; !!user),
          take(1),
      )
      userToFetch$.next(userId)
      return observable
  }
  </code></pre>
  
  <p>But that's ugly and it has multiple troubles:</p>
  
  <ul>
  <li>If i unsubscribe from the observable returned by <code>fetchUser</code> before the timer of <code>bufferTime</code> is finished, it doesn't prevent the fetch of the user. </li>
  <li>If i unsubscribe from all the observables returned by <code>fetchUser</code> before the fetch of the batch is finished, it doesn't cancel the request.</li>
  <li>Error handling is more complex</li>
  <li>etc</li>
  </ul>
  
  <p>More generally: i don't know how to solve the problems requiring <strong>sharing resources</strong> using RxJS. It's difficult to find advanced example of RxJS. </p>