I have been seeing quite a lot of talk on the tweet feeds and blog posts recently about the new Reactive Extensions that are being released. Now I was struggling to get my head around it at first but read this simple blog post which really helped clarify what Rx actually offers. It seems very powerful, and could be a game changer for event processing in the same way Linq was for list data. Really like the drag and drop example in this post as it becomes very clear the intention of the code shown below.
Define the events you wish to monitor
var mouseDown = from evt in Observable.FromEvent<MouseButtonEventArgs>(image, "MouseDown")
select evt.EventArgs.GetPosition(image);
var mouseUp = Observable.FromEvent<MouseButtonEventArgs>(image, "MouseUp");
var mouseMove = from evt in Observable.FromEvent<MouseEventArgs>(image, "MouseMove")
select evt.EventArgs.GetPosition(this);
Then define your query which will tie these events together into a logical form for your requirement (In this case drag and drop)
var q = from imageOffset in mouseDown
from pos in mouseMove.Until(mouseUp)
select new { X = pos.X - imageOffset.X, Y = pos.Y - imageOffset.Y };
And then finally subscribe to the query and perform the action we would like to process.
q.Subscribe(value =>
{
Canvas.SetLeft(image, value.X);
Canvas.SetTop(image, value.Y);
});
What's really cool about all this is that the event subscriptions will be marshalled onto the correct thread thus avoiding cross thread access violations. VERY COOL!