Wednesday, May 18, 2011

WCF + Silverlight + Rx (reactive extensions)

Saw a really nice article on using Reactive extensions with silverlight + wcf : http://abovetheblue.blogspot.com/2010/03/reactive-extensions-silverlight-and-wcf.html

Basically you need to use

  • Observable.FromEvent
  • Take(1) ... to automatically unsubscribe from the call. 
  • Now just make the standard WCF call. 
i.e.: 

public Page()
{
    InitializeComponent();

    CustomersServiceClient client = 
        new CustomersServiceClient();
    IObservable<IEvent<GetCustomersCompletedEventArgs>> observable =
        Observable.FromEvent<GetCustomersCompletedEventArgs>(
            client, "GetCustomersCompleted"
        ).Take(1);

    observable.Subscribe(
        e =>
        {
            if (e.EventArgs.Error == null)
            {
                var customers = e.EventArgs.Result;
                dg.ItemsSource = customers;
            }
        });
    client.GetCustomersAsync();
}

I can think up a nice clean code generator that will make WCF calls with neat error handling. Till then.

Enjoy!

No comments:

Post a Comment