I would like to implement a TextBox where, as you type, results appear instantly in another ListBox. I\'ve been looking for examples with Reactive Extensions (Rx), and all o
This is the kind of approach that I would use in this instance:
var query = Observable.FromEventPattern
(
h => textBox1.TextChanged += h,
h => textBox1.TextChanged -= h)
.Throttle(TimeSpan.FromMilliseconds(100))
.ObserveOnDispatcher()
.Select(x => textBox1.Text)
.DistinctUntilChanged()
.Do(x => listBox1.Items.Clear())
.ObserveOn(Scheduler.Default)
.Select(x => executeSearch(x))
.Switch()
.ObserveOnDispatcher();
query.Subscribe(x => listBox1.Items.Add(x));
The executeSearch
code has the following signature: Func
.
The important part with this query is the final Switch
statement. It turns an IObservable
into a IObservable
by only returning the results of the latest observable.
The calls to .ObserveOnDispatcher()
& .ObserveOn(Scheduler.Default)
ensure that different parts of the observable query happen on the correct threads.