响应式扩展允许我"观察"事件流。例如,当用户在Windows 8搜索窗格中输入他们的搜索查询时,建议请求会一遍又一遍地出现(对于每个字母)。我如何利用响应式扩展来限制请求?
像这样:
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;
};
<<p> 解决方案/strong> 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));
安装RX for WinRT: http://nuget.org/packages/Rx-WinRT/了解更多信息:http://blogs.msdn.com/b/rxteam/archive/2012/08/15/reactive-extensions-v2-0-has-arrived.aspx
有Throttle
和DistinctUntilChanged
方法
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())