2013-05-16 41 views
5

Tiện ích mở rộng phản ứng cho phép tôi "quan sát" một luồng sự kiện. Ví dụ, khi người dùng gõ truy vấn tìm kiếm của họ trong Windows 8 Search Pane, SuggestionsRequested được nâng lên nhiều lần (cho mỗi chữ cái). Làm cách nào để tận dụng Tiện ích mở rộng phản ứng để điều tiết các yêu cầu?Làm cách nào để sử dụng Tiện ích mở rộng phản ứng để tăng tốc SearchPane.SuggestionsRequested?

Something như thế này:

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; 
}; 

Giải pháp

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

Install RX cho WinRT: http://nuget.org/packages/Rx-WinRT/ Tìm hiểu thêm: http://blogs.msdn.com/b/rxteam/archive/2012/08/15/reactive-extensions-v2-0-has-arrived.aspx

Trả lời

4

ThrottleDistinctUntilChanged phương pháp.

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

Bạn có thể muốn/cần sử dụng quá tải khác nhau cho DistinctUntilChanged, ví dụ: sử dụng so sánh bình đẳng khác nhau hoặc quá tải so sánh Func<TSource, TKey>:

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

Điều đó sẽ làm những gì bạn muốn.

+0

@ JerryNixon-MSFT Ồ, xin lỗi vì điều đó :) Nó xuất hiện khi tôi đang duyệt ... Vui vì tôi đã đúng. –

Các vấn đề liên quan