Tuesday, 18 June 2013

Throttling



Throttling Usage:
{MyObservable}.Throttle(TimeSpan.FromSeconds(2))

This will throttle the stream with timespan of 2 seconds. This means that it will buffer events and keep releasing in chunks after every 2 seconds:-




Ok, so after understanding what Throttle does, we can easily throttle our observable:-

var textChangedEvent = Observable.FromEventPattern(txtWord, "TextChanged").Throttle(TimeSpan.FromSeconds(2));


But we have got a problem here. as soon as we introduce throttle, concurrency issues occur. Try and run the application and you will encounter this problem. Since the observable is running on a different thread, it cannot modify UI elements, so we need to somehow make use of the UI synchronization context. So here comes Schedulers, which we will cover in detail in later topics. Lets change the code as follows:-

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            var uiSyncContext = SynchronizationContext.Current;

            var textChangedEvent = Observable.FromEventPattern(txtWord, "TextChanged").Throttle(TimeSpan.FromSeconds(2)).ObserveOn(uiSyncContext);
         
            var disposable = textChangedEvent.Subscribe(_ =>
                {                
                        txtBlock.Text = txtWord.Text;
                }
               );

            textChangedEvent.Subscribe(x =>
                {
                    var count=txtWord.Text.Split(' ').Count();
                    this.Title = "Word Count= " + count + x.GetType().ToString();
                    if(count>=10)
                        disposable.Dispose();
                }
                );
        }

Note: I am intentionally not using Rx Schedulers here to keep things simple.

This will do exactly what we need, update textblock after every two seconds and synchronize with textbox. Another very good place where throttling can be used is where we want to implement functionality like google suggest but we don't want to bug the server with many requests.

No comments:

Post a Comment