If you haven’t heard of Reactive extensions (Rx) for .NET, it’s time to get familar. Rx is extremely cool and once you understand it, it will change the way you write client-side code forever. Instead of providing an overview of Rx, I’m going to urge readers to check out Pencho Popadiyn’s blog post, where he does a much better job of explaining it that I probably could.
Instead, I’m going to demonstrate one practical use for Rx extensions here in my 2 part blog. Yes, 2 parts! That’s how cool I think Rx is. 🙂 And keep in mind that I’m only scratching the surface on the ways Rx can be used. Enough fanfair, let’s get started by building a super simple Silverlight app that updates a ListBox with and without Rx and you be the judge of which is better.
Let’s work backwards by looking at the end result first and then going over how to create it.
Now, here’s how it works…
Step 1: Download and install Rx for Silverlight (link about one page down on the right hand side).
Step 2: In your Silverlight 3 project, Add a reference to the 3 Rx assemblies: System.CoreEx, System.Observable, & System.Reactive.
Note: The 3 files only add ~70K to your .xap file.
Step 3: Create a function that returns a model. For this example, we’ll just have an IEnumerable<String> as our model and I’ll toss in a delay between each item so we can exagerate the difference between Rx and non-Rx.
public static IEnumerable<string> GetModel()
{
for (int i = 0; i < 5; ++i)
{
System.Threading.Thread.Sleep(500);
yield return "Item " + i;
}
}
Step 4: The standard way to put that model into our ListBox would be to assign it (the IEnumerable) to ListBox.ItemsSource. However, for the sake of an apples to apples comparison, I’ll manually loop thru my model and insert each item into an ObservableCollection that is bound to the ListBox.
//MyList.ItemsSource = GetModel();
var items = new ObservableCollection<string>();
MyList.ItemsSource = items;
foreach (string item in GetModel())
items.Add(item);
Step 5: Rx magic time! First, I’ll write similar code as in Step 4 but using Rx…
var items = new ObservableCollection<string>();
MyList.ItemsSource = items;
IObservable<string> observable = GetModel().ToObservable();
observable.Subscribe(item => items.Add(item));
Instead of iterating through the IEnumerable, we create an Observable object from our IEnumerable using the .ToObservable extension method. Then, we subscribe to that observer which tells it to iterate over the collection and run our lamba expression for each item. Bottom line: same result.
Step 6: More Rx magic. Let’s use the power of multi-threading and get our model to be created on a background thread, while we add our items to our observable collection (in order to avoid an invalid cross thread exception). We just have to change the last two lines a little bit..
IObservable<string> observable = GetModel()
.ToObservable(System.Concurrency.Scheduler.NewThread);
observable.ObserveOnDispatcher().Subscribe(item => items.Add(item));
Passing in NewThread to .ToObservable() causes the GetModel function to run on a new thread and .ObserveOnDispatcher() causes our Subscription callbacks to run through the dispatcher (therefore allowing us to update the UI). The end result is a UI left totally responsive while the model is manufactured on it’s own thread and each new model item appears as soon as possible in the UI.
This is certainly possible to do by running GetModel() on a new thread and calling Dispatcher.BeginInvoke for each item. Afterall, this is what Rx is doing internally for us, but I personally think the Rx code is much more readable and writeable.
Next to come: Combining M-V-VM, Rx, and unbuffered REST webservices for clean, easy, and hyper responsive applications that need to communicate with the server!
Very nice walkthrough. Thanks.
Look like the easy way to do background work!
Thanks, I think it is sinking into my brain,
[…] 22, 2010 by Tim Greenfield In my last post I demonstrated how to use reactive extensions in Silverlight to easily build responsive UIs. In this post I am going to expand on that and demonstrate how to use reactive extensions (Rx) from […]
остановить его.- Казнь герцога Энгиенского, – сказал мсье Пьер, – была государственнаянеобходимость; и я именно вижу величие души в том, что Наполеон не побоялся
[…] https://programmerpayback.com/2010/03/11/use-silverlight-reactive-extensions-rx-to-build-responsive-u… […]
busty milf sara jay long movie sex teen sex moans women cambodia porno show me your ass gladiators xxx bewitching housewifes the porno japanese xxx anime tips for sex on bed shower nude sex pornstar randy spears live feed live sex web cams home-schooling elementary sex education curriculum princess resurrection porn best porno magazine gang bang booty nsa sex in dallas texas sakura goku hentai women sex toys gallery ass tonguing
[…] can read more about Rx from here and here (Silverlight […]