Reactive Extensions Instant Search for WPF/MVVM

后端 未结 3 1830
误落风尘
误落风尘 2020-12-19 18:20

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

3条回答
  •  攒了一身酷
    2020-12-19 18:35

    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.

提交回复
热议问题