title: Publish modified array to Observable
body: <h2>The task</h2>
  
  <p>Suppose we implement an Angular service and need to publish an <code>Observable&lt;number[]&gt;</code> to the world:</p>
  
  <pre><code>numbers: Observable&lt;number[]&gt;;
  </code></pre>
  
  <p>We want subscribers to:</p>
  
  <ol>
  <li>receive the last value upon subscription</li>
  <li>receive the whole modified array every time we change and publish it</li>
  </ol>
  
  <p>Since #1, internally the <code>Observable&lt;number[]&gt;</code> should be "at least" a <code>BehaviorSubject&lt;number[]&gt;</code>.</p>
  
  <p>But what about #2? Let's suppose we need to implement a method <code>publishNumbersChange()</code> which is called whenever we need to change and publish the changed array:</p>
  
  <pre><code>private publishNumbersChange() {
      // Get current numbers array
      ...        
  
      changeArray();
  
      // Now publish changed numbers array
      ...
  }
  </code></pre>
  
  <h2>The question</h2>
  
  <p><strong>What is the RxJS 5 pattern to implement the task of publishing modified array based on its previous items?</strong></p>
  
  <p>Since I'm asking it mainly because currently I'm doing Angular stuff, here is the second part of the question:<br>
  <strong>What code does Angular (and the like frameworks based on RxJS) use when they provide an <code>Observable</code> which type parameter is an array to subsequently publish updated array?</strong><br>
  Do they just keep a copy of the currently published array separately?</p>
  
  <h2>Some thoughts</h2>
  
  <p>It seems that storing the underlying array separately, so we always have access to it, is the simplest thing. But at the same time it does not look like a RxJS way (need to have a state outside a RxJS stream).</p>
  
  <p>On the other hand, we could do something like the following:</p>
  
  <pre><code>private publishNumbersChange() {
      // To get the latest value from the stream, we have to subscribe
      const subscription: Subscription = this.numbers.subscribe((numbers: number[]) =&gt; {
          // We got the last value in stream in numbers argument. Now make changes to the array
          changeArray();
  
          // And push it back as a new value to the stream
          this.numbers.next(numbers);
      });
  
      // Also we have to unsubscribe
      subscription.unsubscribe();
  }
  </code></pre>
  
  <p>I see here at least one issue (not counting the complexity\reusability): "race condition" between executing subscription callback and unsubscribing. Looking at that code you can't tell for sure whether the callback would be actually executed. So it doesn't look as a proper way of doing this either.</p>