While working on my todo-list application 2Day, I encountered a situation where Rx came to the rescue. Rx (Reactive Extension) is a framework which has been available for a couple of years now. It is possible to use it on the phone very easily. In this blog post, I share a piece of code which use Rx to implement a specific feature in 2Day.
2Day’s users have requested a search feature. The idea is simple: give the user a new page where he can type some text which then filters his tasks. Here is the feature in action in 2Day:
Even though it seems very basic, I wanted to add an extra feature: perform the search a couple of milliseconds after the user actually stops typing. This prevents the search result to blink while the user types. It turns out it’s very easy to implement this using Rx which is dedicated to manipulate stream of observable items. Here is the code:
var seq = Observable
.FromEventPattern(this.textbox, "TextChanged")
.Throttle(TimeSpan.FromMilliseconds(500))
.ObserveOnDispatcher()
.Subscribe(e =>
{
this.viewmodel.SearchText = this.textbox.Text;
});
The first step is to create the observable sequence using the FromEventPattern method which can turn an event into an observable stream. Then the Throttle method allows to “calm down” the stream, by requiring the specified amount of time to be spent before sending the item in the output stream.
This can be shown using the following diagram:
If the user presses quickly the letters “p”, “a”, “i” and “r” we will start the search only after the specified amount of time and not for each new letter. Notice that the subscribe method does not do a lot of things: it only sets a property on the ViewModel layer which actually performs the search.
Here is a simple yet useful use case for Rx. It’s very nice to have the library available out of the box on the phone. Hope it helps 🙂