ページ

Thursday, February 10, 2011

WebClient by use of Rx ( Reactive Extensions ) for Silverlight.

I don't think the following code is good, but I wanted to check Rx ( Reactive Extensions ) about how it works.
Anyway, It's time for me to do "memo memo" here~.

Reactive Extensions for .NET (Rx)
http://msdn.microsoft.com/en-us/devlabs/ee794896


Preparation

    1. Download a msi file for Rx and then install it.
        ( See the above link for details )

    2. Add the following 3 Rx assemblies to the References in the target project. 
            System.CoreEx
            System.Observable
            System.Reactive





Sample

 public MainViewModel()
 {
   .
   .
   .
  var client = new WebClient();
  client.DownloadStringCompleted += Wc_DownloadStringCompleted;
  try
  {
   client.DownloadStringAsync(new Uri(<URL>, UriKind.Absolute));
  }
  catch(Exception ex)
  {
   MessageBox.Show(ex.Message);
  }
   .
   .
   .
 }

 void Wc_DownloadStringCompleted(object sender, 
                                 DownloadStringCompletedEventArgs e)
 {
   .
   .
   .
 } 

Reactive Extensions

 public MainViewModel()
 {
   .
   .
   .
  var client = new WebClient();
  Observable.FromEvent<DownloadStringCompletedEventHandler, 
                       DownloadStringCompletedEventArgs>(
        h => h.Invoke,
        h => client.DownloadStringCompleted += h,
        h => client.DownloadStringCompleted -= h)
   .Where(e => !e.EventArgs.Cancelled)
   .Retry(3)
   .SelectMany(
        e => (e.EventArgs.Error == null && !string.IsNullOrEmpty(e.EventArgs.Result))
                 ? Observable.Return(e.EventArgs)
                 : Observable.Throw<DownloadStringCompletedEventArgs>(e.EventArgs.Error))
   .Take(1)
   .Subscribe(
        s => Rx_DownloadStringCompleted(s.Result),
        e => MessageBox.Show(e.Message),
       () => { });


  Observable.Return(<URL>)
   .Where(u => !string.IsNullOrEmpty(u))
   .SelectMany(u => Observable.Return(new Uri(u, UriKind.Absolute)))
   .Subscribe(
        s => client.DownloadStringAsync(s),
        e => MessageBox.Show(e.Message),
       () => { });
   .
   .
   .
 }

 void Rx_DownloadStringCompleted(string result)
 {
   .
   .
   .
 } 


I applied Rx to Silverlight RSS Reader Application, and then, I was able to confirm that it worked as usual.


Very interesting~.

No comments:

Post a Comment