下面的代码是否正确编写以根据 Rx 库返回 IObservable?它似乎工作正常,但想知道我是否正确使用它。
private IObservable<SearchResult[]> Search(string query)
{
return Observable.Create((IObserver<SearchResult[]> observer)=>
{
List<SearchResult> result = new List<SearchResult>();
foreach (TestsGroupMeta group in Engine.Groups)
{
string name = group.ToString();
if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
{
result.Add(new SearchResult{ Name = name, Type = "Group"});
}
foreach (TestMethodMeta method in group.Methods)
{
name = method.ToString();
if (name.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) != -1)
{
result.Add(new SearchResult {Name = name, Type = "Method"});
}
}
}
observer.OnNext(result.ToArray());
observer.OnCompleted();
return () => {};
});
}
用法是这样的。
private void SearchForm_Load(object sender, EventArgs e)
{
var textChanged = Observable.FromEventPattern<EventArgs>(txtQuery, "TextChanged")
.Select(_ => ((TextBox)_.Sender).Text);
var searchResult = from query in textChanged
where query.Length >= 3
from result in Search(query)
select result;
_resultsWatcher = searchResult
.Throttle(TimeSpan.FromMilliseconds(200))
.ObserveOn(lvResults)
.Subscribe(resuts =>
{
lvResults.BeginUpdate();
lvResults.Items.Clear();
foreach (SearchResult result in resuts)
{
ListViewItem item = new ListViewItem(result.Name);
item.SubItems.Add(result.Type);
lvResults.Items.Add(item);
}
lvResults.EndUpdate();
});
}
另外,有没有办法从这种方法创建一个 IObservable ?
Task<List<SearchResult>> Search(string query){...}
或者,还有什么其他方法可以在大型数据集上创建异步搜索并从中获得 IObservable。
谢谢