score:1

firstly you need to create an iobservable<string> to abstract the changing the value on your control. the "easiest" way to do this would be with a subject<string>, but most likely its the wrong way to do it.

below is the code you should put into your viewmodel.

idisposable _searchsubscriber =
    _searchstring
         .buffer(timespan.frommillisecond(300))
         .select(searchstring => 
                observable.startasync(canceltoken => 
                      search(searchstring, canceltoken)
                ).switch()
         .observeon(new dispatcherscheduler())
         .subscribe(results => channels = results);

public task<list<channel>> search(string searchterm, cancellationtoken cancel)
{
    var query = dbcontext.channels.where(x => x.name.startswith(searchterm));
    return query.tolistasync(cancel);
}

private behaviorsubject<string> _searchstring = new behaviorsubject<string>("");
public string searchstring
{
    get { return _searchstring.value; }
    set { _searchstring.onnext(value); onpropertychanged("searchstring"); }
}

rx.net is an extremely powerful library, which of course means it does have a bit of a learning curve (although the fact is this is complex because your problem is complex).

let me lay it out...

.buffer(timespan.frommilliseconds(300)) debounces your query, so it only runs the query once every 300 milliseconds.

observable.startasync(canceltoken => search(searchstring, canceltoken)) creates an observable for the search task, which will be cancelled when it is disposed.

select(x => ...).switch() takes only the latest query results, and disposes the last query.

observeon(...) run the following on the scheduler used, make sure you use either dispatchscheduler if you are using wpf, or winformsscheduler if you use winforms.

subscribe(results => ...) do something with the results.


Related Query

More Query from same tag