Rx – for beginners (part 11): ObserveOn

2010/03/29

Rx – for beginners (part 11): ObserveOn

IObservable,IObserver,Rx,Observable this post is the 11th in a series of posts about the new Reactive Framework (Rx).

the series TOC can found here.

in this post we will focus on the ObserveOn…

 

the code sample for this post can be found here.

 

sometime it is important that the observation will occurs on specific thread.

for example GUI application like (WinForm, WPF and Silverlight) throw exception whenever

UI component accessed on thread different than its creation thread.

 

ObserveOn instruct the producer (observable) to call the consumer (observer) on specific thread.

 

having the following Xaml:

Code Snippet
  1. <Window x:Class="ObserveOnSample.Window1"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     Title="Window1" Height="300" Width="300">
  5.     <Grid>
  6.         <TextBlock x:Name="_txt" Text="Not set"/>
  7.     </Grid>
  8. </Window>

if we want to change the Text property of the text box, we mast do it on the Dispatcher thread.

 

doing it we have to add the ObserveOnDispather, as shown in the next snippet (line 8):

Code Snippet
  1. public partial class Window1:Window
  2. {
  3.     public Window1()
  4.     {
  5.         InitializeComponent();
  6.  
  7.         var timeStream = Observable.Interval(TimeSpan.FromSeconds(1));
  8.         var timeStreamDispather = timeStream.ObserveOnDispatcher();
  9.         timeStreamDispather.Subscribe(value => _txt.Text = value.ToString());
  10.     }
  11. }

the sample create interval producer (observable) on line 7.

then it ensure that observation will occurs at the dispatcher thread (line 8).

and subscribe to the synchronized producer (observable) on line 9.

 

Summary

you can use Rx to synchronize your operation to the right thread.

 

the code sample for this post can be found here.

 

Shout it


Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>