Archive

Sharing in RX: Publish, Replay, and Multicast

State is a tricky thing in RX, especially when we have more than one subscriber to a stream. Consider a fairly innocuous setup:

var interval = Observable.Interval(TimeSpan.FromMilliseconds(500));
interval.Subscribe(i => Console.WriteLine("First: {0}", i));
interval.Subscribe(i => Console.WriteLine("Second: {0}", i));

At first glance it might look like I’m setting up two listeners to a single interval pulse, but what’s actually happening is that each time I call Subscribe, I’ve created a new timer to tick values. Imagine how bad this could be if instead of an interval I was, say, sending a message across the network and waiting for a response. Read more