Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On using Publish().RefCount()

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?)

like image 334
Benjol Avatar asked Dec 05 '13 06:12

Benjol


People also ask

What does RefCount do?

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.

What is publish in RxJS?

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.

What connectable Observable?

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.


1 Answers

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.

like image 67
James World Avatar answered Oct 04 '22 17:10

James World