title: RxSwift propagating a value through a chain of flatMaps
body: <p>So I have some RxSwift code where I want to perform a chain of asynchronous operations, all composed using observables. <code>flatMap</code> is the way to do this, and it works great, however it doesn't seem to be able to pass variables down the chain that I can figure out. This is best illustrated by some pseudocode</p>
  
  <p>Assume have 3 functions</p>
  
  <pre><code>class Connection {
      static func establish(address:String) -&gt; Observable&lt;Connection&gt;
      func sendData(data:String) -&gt; Observable&lt;Int&gt; // num bytes written or something
      func close() -&gt; Observable&lt;Void&gt;
  }
  </code></pre>
  
  <p>And I want to call them in a chain such that we connect, send, then close. Something like this</p>
  
  <pre><code>Connection.establish(host)
      .flatMap{ connection in connection.sendData("foo") }
      .flatMap{ numBytes in ????.close() }
      .subscribeNext{ /* all done */ }
  </code></pre>
  
  <p>The problem is that <code>flatMap</code> doesn't pass it's input parameters down the chain, so that the closure passed to <code>subscribeNext</code> doesn't have access to the <code>connection</code> object, and as such it can't call close.</p>
  
  <p>I could do some awful hack like the following, but I'd really rather not!</p>
  
  <pre><code>var connection:Connection?
  Connection.establish(host)
      .flatMap{ c in 
          connection = c
          return c.sendData("foo") 
      }
      .flatMap{ numBytes in connection!.close() }
      .subscribeNext{ /* all done */ }
  </code></pre>
  
  <p>In the C# version of Rx, this is solved by using an overload to <code>SelectMany</code> which takes a second closure, which combines the 2 values (usually into a Tuple) and then <em>that</em> thing is propagated down the chain. I've written this as an extension for RxSwfit, and it works as follows:</p>
  
  <pre><code>Connection.establish(host)
      .flatMap(
          { connection in connection.sendData("foo") },
          combine: { ($0, $1) }) // tupleify
      .flatMap{ (connection, numbytes) in connection.close() }
      .subscribeNext{ /* all done */ }
  </code></pre>
  
  <p>This is all well and good, but my primary question is - Is there a better way to do this which is built into RxSwift as it currently stands?</p>
  
  <p>Additionally, writing this extension method is not simple nor easy. I basically re-implemented FlatMap from scratch by copy/pasting the one in <a href="https://github.com/borland/StockFighterApiClient/blob/master/MiniRxSwift.swift#L322" rel="noreferrer">MiniRxSwift</a> and modifying it. If we have to write this extension, is there a better way to implement it using RxSwift constructs?</p>