Reactive Framework in Silverlight 4
Posted by psoszynski | Posted in Reactive Extensions, Silverlight | Posted on 12-09-2010-05-2008
0
I have just watched a highly recommended video by Wes Dyer on Channel 9 titled “Writing your first Rx Application”. In this screen cast, Wes presents the fundamental concepts behind the the Rx framework, creating a simplistic WPF application. To make my learning experience more fun I decided to follow the screencast and simultaneously “adapt” the code so that it worked in a Silverlight application. It turned out to be very easy. Here is the resulting source code:
{
public MainPage()
{
InitializeComponent();
var mouseDown = from evt in Observable.FromEvent<MouseButtonEventArgs>(this, "MouseLeftButtonDown")
select evt.EventArgs.GetPosition(this);
var mouseUp = from evt in Observable.FromEvent<MouseButtonEventArgs>(this, "MouseLeftButtonUp")
select evt.EventArgs.GetPosition(this);
var mouseMove = from evt in Observable.FromEvent<MouseEventArgs>(this, "MouseMove")
select evt.EventArgs.GetPosition(this);
var q = from start in mouseDown
from delta in mouseMove.StartWith(start).TakeUntil(mouseUp)
.Let(mm => mm.Zip(mm.Skip(1), (prev,cur) =>
new {X=cur.X – prev.X, Y = cur.Y – prev.Y}))
select delta;
q.Subscribe(value => Dispatcher.BeginInvoke(
() => {
Canvas.SetLeft(image, Canvas.GetLeft(image) + value.X);
Canvas.SetTop(image, Canvas.GetTop(image) + value.Y);
}
));
}
}
Alternatively, instead of Despatcher.BeginInvoke(…) we can use the IObservable<T> extension method ObservableOnDispatcher<T>:
{
Canvas.SetLeft(image, Canvas.GetLeft(image) + value.X);
Canvas.SetTop(image, Canvas.GetTop(image) + value.Y);
}
);
which gives the same effect:
