For those of you who are familiar with Reactive Extensions you should know all about observables already, but did you know that there’s another kind of observable sequence – Rx.ConnectableObservable.
The difference between the two types of observable sequences is well explained here, in short, a connectable observable sequence allows you to share the same source sequence of values with multiple subscribers whilst the normal observable sequence gives each subscriber its own sequence of values. Whilst in most cases this difference doesn’t have any practical impacts as each subscribers are given the same values in the same order, however, consider this observable sequence of random numbers between 0 and 1000:
As you can see, each time the iterator is invoked it’ll generate a different value, hence subscribers will receive a different value each time (see demo below):
Instead, if you want to ensure that all the subscribers receive the same values, your best bet is to ‘publish‘ the source:
which returns you a connectable observable that you can then attach subscribers to:
and once you ‘connect‘ to the underlying source, the subscribers will start receiving values from the stream: