Implementing simple instant search with Rx (Reactive Extensions)

Tags: rx, system.reactive, csharp, winforms, .net4, instant-search

Haven't heard of Rx, this could be a little starter tutorial for you.

Rx or Microsoft's Reactive extensions makes life simple when it comes to asychronous programming

My most favorite thing about Rx is how simple it makes instant search! A while ago I asked around on stackoverflow and just architecturing it was so difficult.

So I'm going to go through a dead simple example, where we're going to have an instant search, but, we'll have some dummy data in memory that we're going to search.

Update : I wrote a continuation of this article here where I describe instant search with Rx on a SqlCE database and a nice clean abstraction.

Here's what it'll look like:

Instant Search App

I hope to do a post on searching real data, maybe with sql-compact 4, and then I'll get on to how to write Observable Repositories which makes life easier, especially for Silverlight!

How To:

So head over to Visual Studio and create a new form (or you can download the sample). Add a textbox and listbox like the screenshot.

We need to install Rx-Main and Rx-WinForms from nuget.

You can right click your solution and choose Manage Nuget Packages.. and search and install these.

Visual Studio Package Manager

This is the code then:

What/How/Why? :

The starting point to observables is the Observable class, the FromEventPattern method creates an observable sequence from the TextChanged event of the textbox.

Think of this like a list of notifications coming to you.

We then chain a method call to Throttle (my fav part!), it well, throttles this list of notifications by 500 milliseconds.

Here, for win-forms you need the ControlScheduler class otherwise the throttling doesn't work too well. This class comes from the Rx-WinForms package we added earlier. The Do method just does the metho you want to run, and you send off the text from the the textbox over. Lastly, calling Subscribe starts off the notifications.

Download the Sample here.(1.3MB) It's a clean solution but with the Rx nuget packages.

Hope this was useful!

Comments powered by Disqus