Thursday, December 31, 2009

IObservable (T) and IObserver(T) in .Net 4.0: Implemt push based notification using observer pattern

.Net framework 4.0 is going to come up with two new interfaces IObservable and IObserver. These interfaces is going to give a cleaner way to implement observer pattern in your code. In observer design pattern there are two parties involved. One is observer and another is subject.The subject maintains a list of observers and notifies them in case of change in its state.

In .net framework 4 the implementation of observer pattern can be achieved by implementing two interfaces IObservable and IObserver. The class implementing IObservable plays the role of subject and the class implemeniting IObserver acts as observer.

Let us assume that a 'Blog' has some subscribers who want to be notified after every article posted in the 'Blog'. So we can say that here the readers are subscribers to the 'Blog' and they are observer. On the other hand 'Blog' is the subject or observable. When a new article is posted in the blog subscriber will be notified about the article. The following block of codes will help you to understand you can implement this in .net framework 4.0 with two new interfaces.


namespace ObserverExample
{
class Program
{
static void Main(string[] args)
{
Blog blog = new Blog();
/***********Subscribe to the blog********/
blog.Subscribe(new Subscriber { Name = "Alex" , Email="alex@abc.com"});
blog.Subscribe(new Subscriber { Name = "Kevin", Email = "kevin@abc.com" });
blog.Subscribe(new Subscriber { Name = "Kelly", Email="kelly@mail.com"});

blog.PostArticle();
Console.ReadLine();
}
}

public class Article
{
public string Title
{
get;
set;
}
public string Content
{
get;
set;
}

public string Url
{
get;
set;
}
}

public class Blog : IObservable<Article>
{
List<IObserver<Article>> observers = new List<IObserver<Article>>();
Article _article;

#region IObservable<user> Members
public IDisposable Subscribe(IObserver<Article> observer)
{
observers.Add(observer);
return observer as IDisposable;
}
#endregion

public void PostArticle()
{
_article = new Article { Content="Cleaner way to implement observer", Title="Observer pattern in .net 4.0", Url="http://observer.blog.com"};

/*********Save article and then notify observers*****************/
foreach (IObserver<article> observer in observers)
{
observer.OnNext(_article);
}
}
}

public class Subscriber : IObserver<Article>
{
#region IObserver<Article> Members
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public void OnCompleted()
{
Console.WriteLine("Finished sending notification.");
}

public void OnError(Exception error)
{
Console.WriteLine("Error sending notification");
}

/****************This is the function which will be called to notify observer***************/
public void OnNext(Article value)
{
/*************Writing to console****************/
/************You should write code here according to your notification mechanism to the subscriber/observer ************/
Console.WriteLine("Name:{0} Email:{1}", this.Name, this.Email);
Console.WriteLine("Title:{0}\n Content:{1}", value.Title,value.Content);
}
#endregion
}
}

Though the example is trivial I hope this one will help anyone to understand how to implement observer pattern in a cleaner way in framewok 4.0.

35 comments:

  1. Good article but it would be better if you used code syntax highlighter.

    ReplyDelete
  2. I do not even know how I ended up here, but I thought
    this post was great. I don't know who you are but definitely you're going to a famous blogger
    if you are not already ;) Cheers!

    Feel free to surf to my web blog: entrepreneur ideas for students

    ReplyDelete
  3. Hello would you mind sharing which blog platform you're working with? I'm going to start my
    own blog soon but I'm having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something
    unique. P.S My apologies for being off-topic but I had to
    ask!

    Feel free to surf to my site; pay per click search engine marketing

    ReplyDelete
  4. Just wish to say your article is as astonishing.
    The clarity in your post is just great and i can assume you are an expert on this subject.
    Fine with your permission allow me to grab your feed to keep updated with forthcoming post.
    Thanks a million and please carry on the
    enjoyable work.

    My website ... firmenkonto trotz schufa

    ReplyDelete
  5. Good post! We are linking to this particularly great content on our site.
    Keep up the great writing.

    Check out my webpage: private krankenversicherung studententarif

    ReplyDelete
  6. Greetings, I believe your web site might be having internet browser compatibility issues.
    When I take a look at your web site in Safari, it looks fine but when opening
    in IE, it has some overlapping issues. I simply wanted to provide you
    with a quick heads up! Other than that, wonderful site!

    Check out my homepage :: kredit ohne schufa erfahrung

    ReplyDelete
  7. Spot on with this write-up, I truly think this website needs a great deal
    more attention. I'll probably be returning to read through more, thanks for the information!

    my blog ... bad credit refinancing home loan

    ReplyDelete
  8. I could not refrain from commenting. Very well written!

    Feel free to surf to my web site ... http://nrec.neurologie.uni-tuebingen.de/nrec/SerenaJdf
    Also see my web site - http://www.moveyourmoneyproject.org/node/10806/

    ReplyDelete
  9. I love reading through a post that can make people think.
    Also, thanks for allowing me to comment!

    Feel free to surf to my page products affiliate

    ReplyDelete
  10. I love reading through a post that can make people
    think. Also, thanks for allowing me to comment!

    Feel free to surf to my blog products affiliate
    my site :: the best affiliate program

    ReplyDelete
  11. Why people still make use of to read news papers when in this technological world everything
    is accessible on web?

    my web blog; private krankenversicherung sinnvoll

    ReplyDelete
  12. My family members all the time say that I am killing my time here at
    net, but I know I am getting familiarity daily by reading such pleasant articles or reviews.


    My blog: test krankenkasse
    My page: gesetzliche krankenversicherung vergleich stiftung warentest

    ReplyDelete
  13. That is very fascinating, You are a very professional blogger.
    I've joined your rss feed and sit up for looking for extra of your wonderful post. Also, I have shared your web site in my social networks

    Take a look at my page: can someone with bad credit buy a house

    ReplyDelete
  14. Hi, every time i used to check web site posts here early in the morning, for the reason that i like to gain knowledge of more and more.


    Feel free to visit my blog :: best honeymoon destinations

    ReplyDelete
  15. Why users still use to read news papers when in this technological globe everything is presented on net?


    Also visit my web page ... search engine optimization top

    ReplyDelete
  16. Fastidious replies in return of this difficulty with firm arguments and telling all
    concerning that.

    My website :: paid surveys
    my page > promote products online

    ReplyDelete
  17. What's up to all, how is all, I think every one is getting more from this web site, and your views are pleasant for new visitors.

    Also visit my site: private Krankenversicherung gesetzliche krankenversicherung

    ReplyDelete
  18. Actually when someone doesn't be aware of afterward its up to other visitors that they will help, so here it happens.

    My web blog :: starting A business idea
    Also see my page - business new ideas

    ReplyDelete
  19. My programmer is trying to persuade me to move to .net
    from PHP. I have always disliked the idea because of the costs.

    But he's tryiong none the less. I've been using Movable-type on various websites for about a year and
    am nervous about switching to another platform. I have heard
    excellent things about blogengine.net. Is there a way
    I can import all my wordpress content into it?
    Any help would be greatly appreciated!

    my blog; billige online shops kleidung
    my web page > Designer Outlet Online Shop

    ReplyDelete
  20. It's an amazing paragraph designed for all the online users; they will obtain advantage from it I am sure.

    My page does clickbank work

    ReplyDelete
  21. Hello everybody, here every person is sharing these knowledge, therefore it's pleasant to read this website, and I used to visit this blog everyday.

    Here is my blog post; mom jobs

    ReplyDelete
  22. Usually I do not learn post on blogs, however I wish to say
    that this write-up very compelled me to take a look at and do
    so! Your writing style has been amazed me. Thank you, very great
    post.

    Also visit my page :: home loans bad credit score

    ReplyDelete
  23. We're a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable info to work on. You have done an impressive job and our whole community will be grateful to you.

    Also visit my web page ... Best Reseller Hosting Review

    ReplyDelete
  24. Good day! I know this is somewhat off topic but I was wondering if you knew
    where I could get a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having problems finding one?
    Thanks a lot!

    Also visit my web blog: earn money as an affiliate

    ReplyDelete
  25. It's an remarkable post for all the web users; they will obtain advantage from it I am sure.

    Here is my blog: Http://www.businessdirectory.bz/user_detail.php?u=malinda84

    ReplyDelete
  26. Very nice article, just what I was looking for.



    Also visit my webpage; wechsel private kv in gesetzliche kv

    ReplyDelete
  27. Hmm it appears like your website ate my first comment (it was super long) so I guess I'll just sum it up what I wrote and say, I'm thoroughly enjoying your
    blog. I too am an aspiring blog blogger but I'm still new to everything. Do you have any tips for first-time blog writers? I'd really appreciate it.


    Also visit my page: top web hosting companies

    ReplyDelete
  28. This page definitely has all the information I wanted about this subject
    and didn't know who to ask.

    my web blog: your own business ideas

    ReplyDelete
  29. This is my first time visit at here and i am in fact impressed to
    read all at alone place.

    My web blog Student Private krankenversicherung

    ReplyDelete
  30. Good day! This is my 1st comment here so I just wanted to give
    a quick shout out and say I really enjoy reading your posts.
    Can you suggest any other blogs/websites/forums that
    go over the same subjects? Thank you!

    Visit my web site ... reseller panel

    ReplyDelete
  31. I’m not that much of a internet reader to be honest but your sites really nice, keep it up!
    I'll go ahead and bookmark your site to come back in the future. Cheers

    My weblog; What can home equity loans be used for

    ReplyDelete
  32. Thanks for one's marvelous posting! I certainly enjoyed reading it, you are a great author. I will remember to bookmark your blog and will come back in the future. I want to encourage you continue your great job, have a nice morning!

    Feel free to surf to my web page :: günstig schuhe online

    ReplyDelete
  33. I am in fact delighted to read this web site posts which
    carries tons of useful facts, thanks for providing such information.


    Feel free to visit my web-site private studenten Krankenversicherung

    ReplyDelete
  34. An outstanding share! I've just forwarded this onto a co-worker who has been conducting a little homework on this. And he actually bought me dinner simply because I discovered it for him... lol. So let me reword this.... Thank YOU for the meal!! But yeah, thanks for spending the time to discuss this topic here on your site.

    Check out my weblog best place to get private student loans

    ReplyDelete
  35. Сuггently it ѕeems lіke Expression
    Engine іѕ the toρ blogging рlatform aνailаble right now.
    (from what І've read) Is that what you are using on your blog?

    Stop by my page ... DiamondLinks

    ReplyDelete