title: RxJs avoid external state but still access previous values
body: <p>I'm using RxJs to listen to a amqp queu (not really relevant).</p>
  
  <p>I have a function <code>createConnection</code> that returns an <code>Observable</code> that emits the new <strong>connection</strong> object. Once I have a connection, I want to send messages through it every <strong>1000ms</strong> and after 10 messages I want to close the connection.</p>
  
  <p>I'm trying to avoid external state, but if I don't store the connection in an external variable, how can I close it? See I begin with the connection, then <code>flatMap</code> and push messages, so after a few chains I no longer have the connection object.</p>
  
  <p>This is no my flow but imagine something like this:</p>
  
  <pre><code>createConnection()
    .flatMap(connection =&gt; connection.createChannel())
    .flatMap(channel =&gt; channel.send(message))
    .do(console.log)
    .subscribe(connection =&gt; connection.close()) &lt;--- obviously connection isn't here
  </code></pre>
  
  <p>Now I understand that it's stupid to do that, but now how do I access the connection? I could of course begin with <code>var connection = createConnection()</code></p>
  
  <p>and later on somehow join that. But how do I do this? I don't even know how to ask this question properly. Bottomline, what I have is an observable, that emits a connection, after the connection is opened I want an observable that emits messages every 1000ms (with a <code>take(10)</code>), then close the connection </p>