反应式扩展允许我“观察”一系列事件。例如,当用户在 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