How should one go about implementing a DistinctLatest (and caching) operator in Rx?
<p>I had a question <a href="https://stackoverflow.com/questions/40610584/a-cache-serving-updates-and-new-values-as-distinctlatest-and-full-cache-conten">A cache serving updates and new values as “DistinctLatest” and full cache contents upon subscription</a>, which was well handled by the community. A question was raised that the actual goal of caching and replacing values like defined in the aforementioned question could be defined with a <code>.DistinctLatest</code> operator.</p>

<p>OK! There doesn't seem to be much talk about such an operator. While searching, and thinking about it, I found <a href="https://stackoverflow.com/questions/34145876/reactivex-group-and-buffer-only-last-item-in-each-group">ReactiveX: Group and Buffer only last item in each group</a>, which is kind of close. To mimick the original issue, I tried to write the caching operator as</p>

<pre><code>/// &lt;summary&gt;
/// A cache that keeps distinct elements where the elements are replaced by the latest.
/// &lt;/summary&gt;
/// &lt;typeparam name="T"&gt;The type of the result&lt;/typeparam&gt;
/// &lt;typeparam name="TKey"&gt;The type of the selector key for distinct results.&lt;/typeparam&gt;
/// &lt;param name="newElements"&gt;The sequence of new elements.&lt;/param&gt;
/// &lt;param name="seedElements"&gt;The seed elements when the cache is started.&lt;/param&gt;
/// &lt;param name="replacementSelector"&gt;The replacement selector to choose distinct elements in the cache.&lt;/param&gt;
/// &lt;returns&gt;The cache contents upon first call and changes thereafter.&lt;/returns&gt;
public static IObservable&lt;T&gt; Cache&lt;T, TKey&gt;(this IObservable&lt;T&gt; newElements, IEnumerable&lt;T&gt; seedElements, Func&lt;T, TKey&gt; replacementSelector)
{
    var s = newElements.StartWith(seedElements).GroupBy(replacementSelector).Select(groupObservable =&gt;
    {
        var replaySubject = new ReplaySubject&lt;T&gt;(1);
        groupObservable.Subscribe(value =&gt; replaySubject.OnNext(value));

        return replaySubject;
    });

    return s.SelectMany(i =&gt; i);            
 }
</code></pre>

<p>But doing testing that doesn't seem to do the trick either. It looks like if one subscribe in the beginning the initial values and the updates (and new values) are observed. While if one subscribed at the end, only the replaced seed values are recorded.</p>

<p>Now, I wonder about a general <code>DistinctLast</code> operator, which I think this, but it doesn't work, and then what this "cache" adds is seed values and flattening of the groups, but that's not what the test tells. I also tried some things with grouping and <code>.TakeLast()</code> too, but no dice.</p>

<p>I'd be delighted if anyone had pointers or pondering about this and hopefully this turns out to be something commonly beneficial.</p>