title: Optimize repeated expensive computations in Rxjs given an Observable of Array
body: <p>Given the following script:</p>
  <pre class="lang-js prettyprint-override"><code>type Data = {
    id: string
    value: number
  }
  
  // This is a pure function: given val, res will always be the same
  const veryExpensiveCalc = (val: number) =&gt; {
    const res = // ... 5 seconds of sync computation ...
    return res
  }
  
  const array$ = new ReplaySubject&lt;Array&lt;Data&gt;&gt;(1)
  
  const allComputedValues$ = array$.pipe(
    map(arr =&gt;
      arr.map(item =&gt;
        // I want this veryExpensiveCalc to be performed only when
        // item.value changes for this item.id, or the item was not
        // there before
        veryExpensiveCalc(item.value)
      )
    )
  )
  
  allComputedValues$
    .pipe(
      tap(newStruct =&gt; {
        console.log('newStruct', newStruct)
      })
    )
    .subscribe()
  </code></pre>
  <p>I'd like to optimize how <code>allComputedValues$</code> is calculated. In particular let's say that an item is added or removed to <code>array$</code>, or the order of the elements change: then <code>veryExpensiveCalc</code> is executed again on every item of the array, even though that's not needed at all. I just need <code>allComputedValues$</code> from the previous computation with the result of <code>veryExpensiveCalc</code> applied only to the newly added element (in case of addition).</p>
  <p>What's the best way to write this in a functional reactive fashion? It should work also if there are multiple elements edited/added/removed at the same time (so that <code>veryExpensiveCalc</code> is executed only on the elements that have a different <code>value</code> given the same <code>id</code>).</p>