#VS2015 – Observer Pattern the easy way with #NuGet and #CSharp 6 features

Hola!

These days I’m dealing with a Winforms app who needs tons of love (Thanks Tori!). I’m slowly addidng some stuff like IoC, and I get to a point where I need to upgrade the current implementation of Observer for a better one. Lucky for us, in Net Framework 4.0 the MS team added the cool IObserver<T> interface, however there is some code to be written. And let’s be honest, someones already did it 😉

After a quick search, I found a very cool NuGet package [SimpleBroker]. And the better way to explain the use is with a sample.

In this sample, I have a main view which displays the messages sent from others views. In ugly design mode, probably will be similar to this one.

The Message class is the one, used for communication and it only have 2 properties

In the Send Message view, the Click() event, will create and Publish() an instance of Message.

The main view, has other stuff to do

1. In the Load() event, let’s start a subscription for objects of Message type

2. The subscription will be handled in OnNext(). Which will show line by line the received messages

3. We will close the subscription in the event Closed()

4. in the button Click() we will create and display a new instance of the Send Message view

And using, Bodies Members and String Interpolation the code is very clean, only 25 lines.

Note: Thanks to C# 6 

A live action demo

2015 08 12 Observer

And the Source code in >> https://github.com/elbruno/Blog/tree/master/WindowsFormsApplicationObserver

Saludos @ Madrid

/El Bruno

References

– El Bruno, C#6 Expression Bodied Members https://elbruno.com/2015/07/30/vs2015-c6-using-expression-bodied-members-hell-on-earth/

– El Bruno, C#6 String Interpolation https://elbruno.com/2015/04/20/vs2015-string-interpolation-vs-string-format-your-team-will-love-you/

– MSDN IObserver<T> https://msdn.microsoft.com/en-us/library/dd989239(v=vs.110).aspx

– GitHub SimpleBroker https://github.com/iac249/SimpleBroker

One thought on “#VS2015 – Observer Pattern the easy way with #NuGet and #CSharp 6 features

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.