Home > Code Samples > Rx – Running a function when the user stops typing

Rx – Running a function when the user stops typing

August 18th, 2010 Leave a comment Go to comments

I’ve been playing with Rx (Reactive Extensions) quite a bit lately and I have to say it’s one of the most powerful features added to .Net since LINQ. That probably isn’t too surprising since a lot of people call Rx “LINQ to Events”.

One common task when creating UIs is to call some function, like a filter or search, when the user stops typing. Anyone who has set this up before knows how painful it is but with Rx it’s dead simple.

private IDisposable textBoxObserver;

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    textBoxObserver =
        Observable
        .FromEvent<TextChangedEventArgs>(SomeTextBox, "TextChanged")
        .Throttle(TimeSpan.FromMilliseconds(500))
        .ObserveOnDispatcher()
        .Subscribe(HandleSomeTextBoxTextChanged);
}

void MainWindow_Unloaded(object sender, RoutedEventArgs e)
{
    textBoxObserver.Dispose();
}

private void HandleSomeTextBoxTextChanged(IEvent<TextChangedEventArgs> args)
{
    var tb = ((TextBox)args.Sender);
    var text = tb.Text;

    SomeFunctionYouWantToCallWhenTheUserStopsTyping(text);
}

There are a lot of other really cool uses for Rx so I’ll be posting more soon. Until then you should check out 101 Rx Samples or this simple implementation of drag & drop in Silverlight.

Categories: Code Samples Tags:
  1. Richard Szalay
    January 11th, 2011 at 13:29 | #1

    FYI, it is recommended that use the “Throttle” overload that accepts an IScheduler rather than using the default and then using ObservableOnDispatcher, otherwise you’ll jump over to the task pool and then back again.

    • Bryan Anderson
      January 12th, 2011 at 22:12 | #2

      Thanks, I thought the two methods were equivalent.

  1. No trackbacks yet.