Rx – Sample


Rx – Sample

this post will focus on the Rx Sample operator.


the Sample operation does sampling the observable stream and forward less intensive data stream of the sampled datum.

it can be prove very useful for scenario like handling
accelerometer stream which can produce 60 value per second, in some cases we don’t need such intensity and
our machine resources may be happier to handle only 10 value per seconds.
the same may be apply to video stream analytics and many other scenario.

this is how the marble diagram look like:


as you can see, nothing special it is just a time based filtering.

the Sample’s API is:

Code Snippet
  1. var xs = Observable.Interval(TimeSpan.FromMilliseconds(0.1));
  2. var ys = xs.Sample(TimeSpan.FromMilliseconds(30));

the TimeSpan parameter define the sampling rate.

except of the TimeSpan overload the Sample operator
can be triggered upon a custom timing.

custom triggering is done by using an overload which accept IObservable as it sampling trigger.

the following example is using a random stream of data as the Sample trigger:

Code Snippet
  1. var rndStream = Observable.Create<Unit>(obs =>
  2.     {
  3.         var unsub = new BooleanDisposable();
  4.         Task.Factory.StartNew(() =>
  5.             {
  6.                 var rand = new Random();
  7.                 while (!unsub.IsDisposed)
  8.                 {
  9.                     Thread.Sleep(rand.Next(4000));
  10.                     obs.OnNext(Unit.Default);
  11.                 }
  12.             });
  13.         return unsub;
  14.     });
  15. var xs = Observable.Interval(TimeSpan.FromMilliseconds(0.1));
  16. var ys = xs.Sample(rndStream);
  17. ys.Subscribe(item => Console.Write("{0}, ", item));

as you can see ,at line 16, the xs stream will be sampled at random rate.


Sample is very straight forward operator which bring the ability of reducing stream intensity in cases which a lower data rate is better.

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=""> <s> <strike> <strong>