Reactive Extensions Tips & Tricks

Creating an observable from an event

Observing a generic event such as the StatusChangedEvent (EventHandler<StatusChangedEvent>) is as simple as

var statusChanged = Observable.FromEventPattern<StatusChangedEventArgs>(
                e => KinectSensor.KinectSensors.StatusChanged += e,
                e => KinectSensor.KinectSensors.StatusChanged -= e);

Cast and OfType

Cast and OfType allow us to observe an observable and in the case of Cast will cast each item to the specified type, causing on OnError if the type cannot be cast (due to an InvalidCastException). OfType does much the same except when a type is not castable to the specified type it’s ignored.

Cast in use…

// cast in use, failing due to InvalidCastException
object[] items = new object[3];
items[0] = 23;
items[1] = "Hello";
items[2] = 444;

var o = items.ToObservable().Cast<int>().Subscribe(Console.WriteLine);

The result of the above will be 23, then an error.

OfType in use…

// OfType used, only int's will be output
object[] items = new object[3];
items[0] = 23;
items[1] = "Hello";
items[2] = 444;

var o = items.ToObservable().OfType<int>().Subscribe(Console.WriteLine);

The result of this will be 23 & 44, with the string ignored.