Rx–Scheduling

29 Oct

With Rx, comes the ability to use different schedulers to have different scheduling effects.  By default the following schedulers are provided via the static Scheduler class.

public static CurrentThreadScheduler CurrentThread { get; }
public static DispatcherScheduler Dispatcher { get; }
public static ImmediateScheduler Immediate { get; }
public static NewThreadScheduler NewThread { get; }
public static TaskPoolScheduler TaskPool { get; }
public static ThreadPoolScheduler ThreadPool { get; } 

As we design our classes for testability, yes you do really, if our class uses Rx and uses a scheduler, such as the NewThreadScheduler, this makes it very hard to test our code.

For this blog post, we’ll be ignoring the TestScheduler as this post is more on class design as to testing the code directly.

The simplest solution, and hence the short blog post, is for once, we have a Microsoft library that uses interfaces. 🙂  All schedulers implement IScheduler which means we can wrap up all the static schedulers into an interface and inject them into our class.  For e.g.

public interface ISchedulerService
{
public static IScheduler CurrentThread { get; }
public static IScheduler Dispatcher { get; }
public static IScheduler Immediate { get; }
public static IScheduler NewThread { get; }
public static IScheduler TaskPool { get; }
public static IScheduler ThreadPool { get; } }
}
public class SchedulerService : ISchedulerService
{
public static IScheduler CurrentThread { get { return Scheduler.CurrentThread; } }
public static IScheduler Dispatcher { get { return Scheduler.Dispatcher ; } }
public static IScheduler Immediate { get { return Scheduler.Immediate ; } }
public static IScheduler NewThread { get { return Scheduler.NewThread ; } }
public static IScheduler TaskPool { get { return Scheduler.TaskPool ; } }
public static IScheduler ThreadPool { get { return Scheduler.ThreadPool ; } }
}

Now that our scheduler service is interfaced out, this means we can now mock out the ISchedulerService in our tests.

Simple, but neat.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: