title: In a Combine Publisher chain, how to keep inner objects alive until cancel or complete?
body: <p>I've created a Combine publisher chain that looks something like this:</p>
  <pre><code>let pub = getSomeAsyncData()
             .mapError { ... }
             .map { ... }
             ...
             .flatMap { data in 
                 let wsi = WebSocketInteraction(data, ...)
                 return wsi.subject
             }
             .share().eraseToAnyPublisher()
  </code></pre>
  <p>It's a flow of different possible network requests and data transformations. The calling code wants to subscribe to <code>pub</code> to find out when the whole asynchronous process has succeeded or failed.</p>
  <p>I'm confused about the design of the <code>flatMap</code> step with the <code>WebSocketInteraction</code>. That's a helper class that I wrote. I don't think its internal details are important, but its purpose is to provide its <code>subject</code> property (a <code>PassthroughSubject</code>) as the next Publisher in the chain. Internally the <code>WebSocketInteraction</code> uses <code>URLSessionWebSocketTask</code>, talks to a server, and publishes to the <code>subject</code>. I like <code>flatMap</code>, but how do you keep this piece alive for the lifetime of the Publisher chain?</p>
  <p>If I store it in the outer object (no problem), then I need to clean it up. I could do <em>that</em> when the <code>subject</code> completes, but if the caller <em>cancels</em> the entire publisher chain then I won't receive a completion event. Do I need to use <code>Publisher.handleEvents</code> and listen for cancellation as well? This seems a bit ugly. But maybe there is no other way...</p>
  <pre><code>.flatMap { data in 
      let wsi = WebSocketInteraction(data, ...)
      self.currentWsi = wsi  // store in containing object to keep it alive.
      wsi.subject.sink(receiveCompletion: { self.currentWsi = nil })
      wsi.subject.handleEvents(receiveCancel: {
          wsi.closeWebSocket()
          self.currentWsi = nil
      })
  </code></pre>
  <p>Anyone have any good &quot;design patterns&quot; here?</p>
  <p>One design I've considered is making my own <code>Publisher</code>. For example, instead of having <code>WebSocketInteraction</code> vend a <code>PassthroughSubject</code>, it could conform to <code>Publisher</code>. I may end up going this way, but making a custom Combine <code>Publisher</code> is more work, and the documentation steers people toward using a subject instead. To make a custom Publisher you have to implement some of things that the <code>PassthroughSubject</code> does for you, like respond to demand and cancellation, and keep state to ensure you complete at most once and don't send events after that.</p>
  <p>[Edit: to clarify that <code>WebSocketInteraction</code> is my own class.]</p>