Saturday, November 21, 2009

Reactive Extensions - Much simpler asynchronous and event based programming


Reactive Extensions helps developers write asynchronous and event based operations in a much simpler way. The user must specify a SynchronizationContext to which the Rx messages are sent. For e.g: If you are using a console app, you should specify the Context as
Observable.Context = SynchronizationContexts.ReactiveEventLoop
For WPF applications your Context will be
Observable.Context = SynchronizationContexts.CurrentDispatcher;

You can write subscriptions to your control events using Rx like
Observable.FromEvent<RoutedEventArgs>(button1, "Click").Subscribe(x => this.Close());

Or
var __StartTimer = button2.GetClickEvents().Subscribe(x => MessageBox.Show("Starting timer..."));
where GetClickEvents is an extension method on UIElements to track clicks on them
public static IObservable<IEvent<RoutedEventArgs>> GetClickEvents(this UIElement uiElement)
{
     return Observable.FromEvent<RoutedEventArgs>(uiElement, "Click");
}

No comments: