RX Replay’s Slow Consumer “Problem”

What is Replay?

We have been using RX for some time now although we still get caught out on the intricate details.  Replay is an extremely useful caching mechanism that allows streams to replay previous entries for new subscriptions, based on count, time or a mixture of both.

Under the covers it’s a multicast with a replay subject:

Observable.Multicast<TSource, TSource>(source, new ReplaySubject(bufferSize))

The Problem

We stumbled across this one the other day.  Lets assume we have our cached replay subject which is connected.  When subscribing to the replay subject, the buffer is sent out within a lock internally.  This means consumers will be delayed from getting their value.

Here is an example:

var stream = Observable.Return(100).Replay(1);

Task.Factory.StartNew(() =>
{
    stream.Subscribe(_ =>
    {
       Thread.Sleep(6000);
       Console.WriteLine("Finished sleeping!");
    });
});

Task.Factory.StartNew(() => stream.Subscribe(_ => Console.WriteLine("Received cached value")));

stream.Connect();

In this case, the console output will look like so (Note the second subscription only ticks after the first one has finished processing its tick):

Finished sleeping!
Received cached value.

The important note to take away is that a slow consumer, could delay subsequent streams from getting their values.

Potential Solutions

Get off the thread, especially when its slow/blocking etc.  There are various approaches to this:

  1. Make the code in the subscribe asyncronous, for example, change the Thread.Sleep(6000) to an await Task.Delay(6000); or run the subscribe code in a new task, if the ordering is not important.
  2. Add an ObserveOn (after the replay) with a scheduler that changes the thread (Generally a bad idea, as the new thread will be cached for the lifetime of the subscription).
  3. A SubscribeOn wouldn’t have any affect here, since its the connect that perform the underlying subscription, which is then shared.
  4. Something else?  I would be keen to hear of any other approaches to resolve this issue.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s