Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Sunday, 30 September 2012

Listening to a single value from an Rx observable sequence

Posted on 08:33 by Unknown
I have an observable sequence and I want to observe only a defined number of values, the number is immaterial, the important part is the fact I don't want to be notified of any further values.

How can this can be achieved?

The answer is easy, use the Rx extension method Take, it'll return the required number of values only. A simple example:

   1:  Observable.FromEventPattern<RoutedEventArgs>(clickButton, "Click")
   2:      .Take(1)
   3:      .ObserveOn(Scheduler.CurrentThread)
   4:      .Subscribe(vt => Debug.WriteLine("{0}: Click called...", ++count));

When the button is clicked in the UI it produces a line in the output window in visual studio:
So using the Take method I can limit the number of observations irrespective of the number of times I click the 'Click Me!' button:

   1:  Observable.FromEventPattern<RoutedEventArgs>(clickButton, "Click")
   2:      .Take(1)
   3:      .ObserveOn(Scheduler.CurrentThread)
   4:      .Subscribe(vt => Debug.WriteLine("{0}: Click called...", ++count));
I was then wondering, and this is the reason for the post:

What's happened to the under lying subscription, has it been disposed?

The seems very similar to a previous post about Rx subscribers and what happens to subscriptions when the OnCompleted is invoked by the disposing the under lying stream. I suspect the answer is 'I don't have anything to worry about, it will all be disposed automatically'.

Lets find out by assigning the subscription to a variable and when the form is closed check the internals of the subscription - yes I am mixing metaphors for .Net event handling ;)
Okay, wasn't expecting that! The under lying composite disposable hasn't been disposed as I was expecting...

I was really expecting it to be automatically disposed at this point, I wonder if adding an OnCompleted implementation for the subscription makes any difference:
So now the subscription is being disposed automatically...

WTF! - How does defining an OnCompleted method mean it can be disposed? Surely what defines it as being eligible for disposing is we're using the Take method with a value of 1.

Now you could say:

'Why worry, I'm sure Rx will take care of it...'

I say anything I create\instantiate which is disposable I am responsible for make sure it is cleaned-up, and this is especially important if you have transient scopes which are regularly being created and destroyed.

Also, the fact I'm using the FromEventPattern extension is not important, the behaviour of the Take method is.
Read More
Posted in .Net, Development, Disposable, Rx | No comments

Saturday, 22 September 2012

Applying LINQ principles to business logic

Posted on 10:27 by Unknown
This was inspired by a conversation I was having with @leeoades & @hamishdotnet at work earlier this week, we were discussing the use of Yield keyword to short-cut method execution. Lee has a great post about sequences here. I wanted to get down how my thinking about the Yield keyword has now changed.

Historically I've always thought about using the yield when I'm defining a custom enumerator method, something like GetFooEnumerator - typically I'd have placed this on some kind of model object to allow the easy iteration of some child model instances. Lee was saying why not use yield where ever you have the following usage pattern:

   1:  public IEnumerable<int> Range(int start, int end)
   2:  {
   3:      var numbers = new List<int>();
   4:      for (var i = start; i < end; i++)
   5:      {
   6:          // Do some business logic here...
   7:          numbers.Add(i);
   8:      }
   9:   
  10:      return numbers;
  11:  }

When ever you have a method which internally creates & populates a collection and then returns the collection why not use yield to make it more efficient?

This got me thinking, what kind of improvement efficiency are we talking about?

Time for a quick test, first we need a couple of methods to compare, first one very similar to above and another making use of the yield keyword but both achieving the same logic - returning a collection of numbers to the caller:

   1:  public class Numbers
   2:  {
   3:      public IEnumerable<int> Range(int start, int end)
   4:      {
   5:          var numbers = new List<int>();
   6:          for (var i = start; i < end; i++)
   7:          {
   8:              numbers.Add(i);
   9:          }
  10:   
  11:          return numbers;
  12:      }
  13:   
  14:      public IEnumerable<int> YieldRange(int start, int end)
  15:      {
  16:          for (var i = start; i < end; i++)
  17:          {
  18:              yield return i;
  19:          }
  20:      }
  21:  }

Then a test program - use each method as part of LINQ call to validate the returned sequences contain the number 420:

   1:  static void Main(string[] args)
   2:  {
   3:      Console.WriteLine();
   4:   
   5:      var numbers = new Numbers();
   6:   
   7:      var sw = new Stopwatch();
   8:      sw.Start();
   9:      var found1 = numbers.Range(0, 999).Any(n => n == 420);
  10:      sw.Stop();
  11:   
  12:      Console.WriteLine("Normal Loop: ticks = " + sw.ElapsedTicks);
  13:   
  14:      var sw2 = new Stopwatch();
  15:      sw2.Start();
  16:      var found2 = numbers.YieldRange(0, 999).Any(n => n == 420);
  17:      sw2.Stop();
  18:             
  19:      Console.WriteLine("   Yielding: ticks = " + sw2.ElapsedTicks);
  20:      Console.ReadLine();
  21:  }

Running this up I got the following output!
What!

I wasn't expecting it to be slower, after all the YeildRange method only has to iterate 420 times before finding a match where as the Range method has to iterate over all 1000 numbers before returning...

Then @hamishdotnet pointed out the cost of yielding and I remembered the chapter in Jon Skeet's C# In Depth about iterator blocks and how a set of classes are created by the compiler when ever you use the yield keyword.

Then I had the realisation the methods didn't really have any 'business logic' - DOH!

Basically the 2 implementations don't do anything, so to simulate this I put a Thread.Sleep in to represent an I/O or processor bound call:

   1:  public class Numbers
   2:  {
   3:      public IEnumerable<int> Range(int start, int end)
   4:      {
   5:          var numbers = new List<int>();
   6:          for (var i = start; i < end; i++)
   7:          {
   8:              System.Threading.Thread.Sleep(10);
   9:              numbers.Add(i);
  10:          }
  11:   
  12:          return numbers;
  13:      }
  14:   
  15:      public IEnumerable<int> YieldRange(int start, int end)
  16:      {
  17:          for (var i = start; i < end; i++)
  18:          {
  19:              System.Threading.Thread.Sleep(10);
  20:              yield return i;
  21:          }
  22:      }
  23:  }

More promising results now...

So what do I mean by 'Applying LINQ principles to business logic'?

By thinking about concepts such as 'lazy evaluation' & 'materialization' when designing your methods you allow for the opportunities for your code to be more efficiently executed when used as part of any linq queries.
Read More
Posted in C#, Development, LINQ | No comments

Tuesday, 18 September 2012

How do I flatten an enumerable IObservable to IObservable?

Posted on 13:44 by Unknown
The title of this post should be 'How do I flatten IObservable<IEnumerable<T>> to IObservable<T>?'

But blogger says 'no'...

This seems like a simple & legitimate Rx question and if you're one of the initiated it's very easy simple.

It came up the other day because a back-end service we're talking to returned an array of stuff and we wanted to flatten it into a stream of single values we could observe.

So what do I replace CONVERT_SOMEHOW with?
voilà...

   1:  IObservable<int[]> numbers = Observable.Return(new[] {1, 2, 3, 4, 5});
   2:   
   3:  IObservable<int> number = numbers.SelectMany(n => n);

In a simple app:
produces the following output:
Read More
Posted in .Net, C#, Developement, Rx | No comments

Saturday, 15 September 2012

Does the Rx subscriber get disposed when OnCompleted is called?

Posted on 06:19 by Unknown
We use an implementation of an observable command - ObservableCommand<T> in our view models not only to wire the actions of controls defined in the XAML but to allow the other interested parties to be notified when the command has executed.

We were wondering what happens when the observable command is disposed, does the OnCompleted method for the subscribers get called and importantly are the subscribers disposed?

Our observable command has an implementation similar to this:

   1:   
   2:  public class ObservableCommand<T> : ICommand, IObservable<T>
   3:  {
   4:      private readonly Subject<T> _subj = new Subject<T>();
   5:   
   6:      public void Execute(object parameter)
   7:      {
   8:          _subj.OnNext((T)parameter);
   9:      }
  10:   
  11:      public bool CanExecute(object parameter)
  12:      {
  13:          return true;
  14:      }
  15:   
  16:      public event EventHandler CanExecuteChanged;
  17:   
  18:      public IDisposable Subscribe(IObserver<T> observer)
  19:      {
  20:          return _subj.Subscribe(observer);
  21:      }
  22:  }

To test question I used a simple class which generates numbers, this exposes 2 methods one to set up a subscription and the other to shut down the under lying stream, this wouldn't be any good for 'real' code but will do for a test:

   1:  public class NumberGenerator
   2:  {
   3:      private readonly TimeSpan _interval = TimeSpan.FromMilliseconds(500);
   4:      private IObserver<int> _stream;
   5:   
   6:      public IObservable<int> Generate()
   7:      {
   8:          var number = 42;
   9:   
  10:          return Observable.Create<int>(o =>
  11:          {
  12:              _stream = o;
  13:              return Observable.Timer(DateTime.Now.Add(_interval), _interval)
  14:              .Subscribe(l =>
  15:              {
  16:                  var currentNumber = number;
  17:                  number = number + 1;
  18:   
  19:                  _stream.OnNext(currentNumber);
  20:              });
  21:          });
  22:      }
  23:   
  24:      public void Complete()
  25:      {
  26:          _stream.OnCompleted();
  27:      }
  28:  }

This was then tested with following program, notice I pass in an Action<T> for the completed action to the Subscribe method:

   1:  internal class Program
   2:  {
   3:      private IObservable<long> _underlying;
   4:   
   5:      private static void Main(string[] args)
   6:      {
   7:          var generator = new NumberGenerator();
   8:   
   9:          var disposable = generator.Generate()
  10:              .Subscribe(n => Console.WriteLine("Number: " + n), () => Console.WriteLine("Completed..."));
  11:   
  12:          Console.ReadLine();
  13:   
  14:          generator.Complete();
  15:   
  16:          Console.ReadLine();
  17:      }
  18:  }

It sets up a subscription on a background thread, the generator then starts producing values every couple of seconds (on another background thread). These are recieved and outputted to the console. Whilst this is happening the main thread is blocked by the first call Console.ReadLine method. Once the enter key is pressed the the internal under lying stream in the generator is shut down and hopefully the OnCompleted method will be called for the subscriber and output "Completed..."

Did OnCompleted get called?

Yes...

So the title question is 'Does the Rx subscriber get disposed when OnComplete is called?'

Yes...

To check this lets look inside the returned IDisposable for the test program:
Debugging the app with a breakpoint on the second Console.ReadLine method, you can see the disposable local variable has been disposed:

So when the under lying stream in Rx is shutdown then all of the subscribers will have their OnCompleted methods called and will be disposed of automatically - perfect!
Read More
Posted in .Net, Development, Disposable, Rx | No comments

Monday, 3 September 2012

Using PostSharp for AOP with Reactive Extensions - update

Posted on 13:34 by Unknown
After digging further into the use of AOP with Reactive Extensions my first post about can be improved by using the Do method instead of the Subscribe method on the IObservable<T> inside the AOP aspect OnExit method.

Why?

The previous implementation I gave would worked well for a hot observable, but for a cold observable this wouldn't apply as it would instantiate a new stream for each subscription setup in the aspect - Lee campbell has a good definition for hot & cold observables.

This means the OnExit method changes from:
to:
There isn't much difference in the implementation, the significant part is re-assigning the ReturnValue for the method execution arguments.

Read More
Posted in AOP, C#, Development, Rx | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ▼  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ▼  September (5)
      • Listening to a single value from an Rx observable ...
      • Applying LINQ principles to business logic
      • How do I flatten an enumerable IObservable to IObs...
      • Does the Rx subscriber get disposed when OnComplet...
      • Using PostSharp for AOP with Reactive Extensions -...
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile