On using Publish().RefCount()

c#, system.reactive

Solution

You do quite often want to do this. In fact I wrote an article on this very point. The reason why it isn't the default is simply that it isn't required all the time (and is easier to omit than switch off); there are many cases where it just adds overhead and there are more than a few cases where Publish() with connection control is needed because the subscriber count can fall to zero and re-subscribing would have unintended side effects, particularly (as you said) when dealing with cold observables.

Problem

I find myself often wanting to use `Publish().RefCount()` to 'protect my sources'. For example, when translating some incoming IObservable json into two IObservable properties: ``` var anon = source.Select(TranslateToAnonObject); this.Xs = anon.Select(GetXFromAnonObject); this.Ys = anon.Select(GetYFromAnonObject); ``` To avoid performing the translation twice, I'd be tempted to put a `Publish().RefCount()` behind the anon definition. And same thing for both property values, to avoid performing the `Get..` functions separately for each subscriber. The thing is, it's getting to the point where I can't really see many situations where I wouldn't want this. But if that was right, it would surely be the default in Rx. What am I thinking wrong? (Thinks: is it because I'm almost exclusively working with 'hot' observables?)

Original source