Skip to content

Instantly share code, notes, and snippets.

@bobbychopra
Last active October 24, 2015 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobbychopra/0c68ccc63ed80790b4b9 to your computer and use it in GitHub Desktop.
Save bobbychopra/0c68ccc63ed80790b4b9 to your computer and use it in GitHub Desktop.
download from http://www.math.sjsu.edu/~foster/dictionary.txt
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TypeAheadComboWithRx
{
public partial class Form1 : Form
{
public string[] words { get; set; }
public Form1()
{
InitializeComponent();
var sr = new System.IO.StreamReader("dictionary.txt");
words = sr.ReadToEnd().Split('\n');
sr.Close();
//cmbTypeAhead.KeyDown
var keydowns = Observable.FromEventPattern(k => cmbTypeAhead.TextChanged += k, k => cmbTypeAhead.TextChanged -= k);
var observable = keydowns
.Select(b => cmbTypeAhead.Text)
.Do(b => DebugWrite(" before throttle .. " + b))
.Throttle(TimeSpan.FromMilliseconds(700))
.DistinctUntilChanged()
.Do(b => DebugWrite(" after throttle .. " + b))
.Select(b =>
Observable.Create<IList<string>>(obs =>
{
obs.OnNext(GetResults(b).ToList());
return Disposable.Empty;
}).SubscribeOn(ThreadPoolScheduler.Instance));
observable
.Switch()
.ObserveOn(new ControlScheduler(this))
.Subscribe(a =>
{
DebugWrite(" results " + a.Count);
cmbTypeAhead.DataSource = a;
cmbTypeAhead.DroppedDown = true;
});
}
public void DebugWrite(string input)
{
var color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("{2} Thread: {0} .. {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, input, DateTime.Now.ToLongTimeString());
Console.ForegroundColor = color;
}
public IEnumerable<string> GetResults(string input)
{
DebugWrite("\t getting ... " + input);
System.Threading.Thread.Sleep(10000);
var matches = words.Where(s => s.StartsWith(input)).ToList();
if (matches.Any() && matches.First() != input)
matches.Insert(0, input);
return matches;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment