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?)
The RefCount operator automates the process of connecting to and disconnecting from a connectable Observable. It operates on a connectable Observable and returns an ordinary Observable. When the first observer subscribes to this Observable, RefCount connects to the underlying connectable Observable.
RxJS publish() operator is a multicasting operator that returns a ConnectableObservable, a variety of Observable that waits until its connect method is called before it begins emitting items to those Observers that have subscribed to it.
A connectable Observable resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only when the Connect operator is applied to it. In this way you can wait for all intended observers to subscribe to the Observable before the Observable begins emitting items.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With