Google Guava EventBus Pubisher Subscriber
Google Guava EventBus which allows communiation between componets in publish-subscriber without registering component with one another. It’s has been designed as an alternative approach for Java event process where explicit registration needed. Below I will show you very simple example with one publisher and two subscriber weather reporting.
Note: To user Google Guava you will need its jar which you can download latest verion form maven site here
As google don’t impose extending class or implement interface. It’s very simple to write publisher and subscriber as you see below:
- Create subscriber1:
- Create subscriber2:
In both subscriber class I have defined two variable temp and weathertype and its getter and setter. Only difference is our setter method have subscriber evnet with @
- Now let’s create Publisher class. For this I will create java main class which will act as publisher including printing subscriber event receive information.
- As you see in WeatherReportPublisher.java class we have instantiated EventBus and registered two subscribers. EventBus is publisher now whatever he will publish subscriber is listening so it will print out the result. If you run WeatherReportPublisher.java you will see below output: