下面的代码是否正确写入以返回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();
});
}
此外,有没有一种方法可以从这样的方法创建IOobservable?
Task<List<SearchResult>> Search(string query){...}
或者,还有什么其他方法可以在大型数据集上创建异步搜索并从中获得IOobservable
Thx
您可以从任务中创建一个可观察的
Task<List<SearchResult>> SearchAsync(string query){...}
var observable = Observable.FromAsync<List<SearchResult>>(()=> SearchAsync(query));
如果您的函数将来只返回1个结果,请考虑使用Task?
public async Task<SearchResult[]> SearchAsync(string query){ }