5

反应式扩展允许我“观察”一系列事件。例如,当用户在 Windows 8 搜索窗格中键入他们的搜索查询时,会一遍又一遍地提出 SuggestionsRequested(针对每个字母)。如何利用 Reactive Extensions 来限制请求?

像这样的东西:

SearchPane.GetForCurrentView().SuggestionsRequested += (s, e) =>
{
    if (e.QueryText.Length < 3)
        return;
    // TODO: if identical to the last request, return;
    // TODO: if asked less than 500ms ago, return;
};

解决方案

System.Reactive.Linq.Observable.FromEventPattern<Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs>
    (Windows.ApplicationModel.Search.SearchPane.GetForCurrentView(), "SuggestionsRequested")
    .Throttle(TimeSpan.FromMilliseconds(500), System.Reactive.Concurrency.Scheduler.CurrentThread)
    .Where(x => x.EventArgs.QueryText.Length > 3)
    .DistinctUntilChanged(x => x.EventArgs.QueryText.Trim())
    .Subscribe(x => HandleSuggestions(x.EventArgs));

为 WinRT 安装 RX:http: //nuget.org/packages/Rx-WinRT/ 了解更多信息:http: //blogs.msdn.com/b/rxteam/archive/2012/08/15/reactive-extensions-v2- 0-已到达.aspx

4

1 回答 1

4

ThrottleDistinctUntilChanged方法。

System.Reactive.Linq.Observable.FromEventPattern<Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs>
    (Windows.ApplicationModel.Search.SearchPane.GetForCurrentView(), "SuggestionsRequested")
    .Throttle(TimeSpan.FromMilliseconds(500), System.Reactive.Concurrency.Scheduler.CurrentThread)
    .Where(x => x.EventArgs.QueryText.Length > 3)
    .DistinctUntilChanged(x => x.EventArgs.QueryText.Trim())
    .Subscribe(x => HandleSuggestions(x.EventArgs));

您可能希望/需要对 使用不同的重载DistinctUntilChanged,例如使用不同的相等比较器或Func<TSource, TKey>重载:

.DistinctUntilChanged(e => e.QueryText.Trim()) 

那会做你想做的事。

于 2013-05-16T15:02:31.903 回答