title: iOS - Batch (coalesce) network requests to a particular resource . Cooperation between NSURLSession , NSURLRequest etc
body: <p>I have a highly asynchronous environment and many modules which may request a particular network resource (such as an access token and perhaps indirectly through transitive requests).</p>
  
  <p>For instance many places in code could "simultaneously" do calls to send analytics:</p>
  
  <pre><code>// module 1
  [Analytics sendAnalytics:module1Analytics];
  
  
  // module 2
  [Analytics sendAnalytics:module2Analytics];
  
  ...
  </code></pre>
  
  <p>Analytics requests require a valid access token and the sending code may contain special care for an expired access token that should be renewed</p>
  
  <pre><code>+(void)sendAnalaytics:(Analytics)analyticsPayload {
      //... setup code ...
      NSURLRequest *analyticsRequest = // Analytics NSURLRequest with a special access token
      // the network request to send the analytics
      [[MyNSURLSession dataTaskWithRequest:analyticsRequest completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error)){
         if (error == 401) {
            get new access token
            // re-send the same request
            [self sendAnalaytics:analyticsPayload];
         }
         // ....
  }] resume];
  }
  </code></pre>
  
  <p>I don't want to request the same resource simultaneously. I want to batch the call for the same resource if it is already running.</p>
  
  <pre><code>// batch this call to only happen once if already running
     NSURLRequest *accesstoken = ...
     ....
  </code></pre>
  
  <p>Also the access token should never be cached (using the "<code>NSURLCache</code>" et.al mechanisms. )</p>
  
  <p>There are other request such as the "access token" request which should be batched together (for instance a request for an image). I need to optimize the network access so that I am not doing redundant requests.</p>
  
  <p>Is there a builtin mechanism supplied by the <code>NSURL</code> loading system  without resorting to collecting the requests myself?</p>