Before going through this post, please have a look here and here to get familiar with Publisher/Subscriber Model.
This post will give you code snippets on how I implemented the above model. I built 3 components,
1) PubSubService
2) PubSubClient
3) Publisher