Let's say you need to implement an automatic search box, but the search operation is somewhat costly, like sending a web request or hitting up a database. You may want to limit the amount of search being done.
For example, the user is typing "C# Reactive Extensions" in the search box :
IObservable<string> TypingSearchText()
{
return Observable.Create<string>(o =>
{
const string SearchText = "C# Reactive Extensions";
var builder = new StringBuilder();
foreach (var c in SearchText)
{
builder.Append(c);
// notify that the search text has been changed
o.OnNext(builder.ToString());
// pause between each character to simulate actual typing
Thread.Sleep(125);
// spent some time to think about the next word to type
if (c == ' ')
Thread.Sleep(1000);
}
o.OnCompleted();
return () => { /* nothing to dispose here */ };
});
}
Now, we don't want to perform the search every time the user presses a key. Instead, it will be done whenever the user stops typing longer than half a second :
TypingSearchText()
// print the changes
.Do(x => Console.WriteLine("Typing: " + x))
// ignore changes that happens within 500ms of each other
.Throttle(TimeSpan.FromMilliseconds(500))
// some costly operation
.Subscribe(x => Console.WriteLine("Searching: " + x));
Output :
Typing: C
Typing: C#
Typing: C#
Searching: C#
Typing: C# R
Typing: C# Re
...
Typing: C# Reactive
Typing: C# Reactive
Searching: C# Reactive
Typing: C# Reactive E
Typing: C# Reactive Ex
...
Typing: C# Reactive Extension
Typing: C# Reactive Extensions
Searching: C# Reactive Extensions