0

下面的代码是否正确编写以根据 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。

谢谢

4

1 回答 1

0

你可以从任务中创建一个可观察的,

Task<List<SearchResult>> SearchAsync(string query){...}

var observable = Observable.FromAsync<List<SearchResult>>(()=> SearchAsync(query));

如果您的函数将来仅返回 1 个结果,请考虑改用 Task?

public async Task<SearchResult[]> SearchAsync(string query){ }
于 2013-08-14T07:36:25.763 回答