2013-05-16 78 views
5

反應性擴展允許我「觀察」一系列事件。例如,當用戶在Windows 8搜索窗格中鍵入搜索查詢時,SuggestionRequested會一遍又一遍(每個字母)引發。我如何利用Reactive Extensions來抑制請求?如何使用Reactive Extensions來限制SearchPane.SuggestionsRequested?

事情是這樣的:

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-has-arrived.aspx

回答

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()) 

會做你想要什麼。

+0

@ JerryNixon-MSFT哦,對不起,這是:)當我瀏覽時彈出...很高興我是對的。 –

相關問題