As android developers we face difficulties on decoupling different parts in android application. To overcome this difficulties, the Square has introduced an event bus for android called Otto. In this post I will demonstrate how to use Otto event bus with IntentServices
in Restful android client. This code can be more optimized. This publish-subscribe style can be used to decouple many other components except the Services. This is just a sample implementation to demonstrate Event Bus concept with IntentService
, except ResultReceiver
usage with Services
.
This is more interesting when it comes to event bus. Because the same results set will be available to multiple components by publishing it on event bus. The required component should subscribe to receive the results. This is more robust than the traditional java event listners and will provide more flexibility.
We can initiate the Bus object according to the requirement of our application. It is not required to be singleton or a single Event Bus instance. As per the requirement you can use multiple Event Bus instances for different purposes. Now will see how to implement Event Bus using the Otto library.
Add the Otto dependancy to build.gradle file
|
|
Create BusProvider class to initiate the Event Bus
|
|
Next we need to subscribe the component(Fragments, Activity, Objects, etc…) where we need to receive the event post. I have created a Fragment which will start a IntentService for data fetching from a webservice and to post the data in event bus.
|
|
|
|
This method will be invoked when the event posted to the bus. Important to add Subscribe annotation. Wherever you have Subscibe with this method(same parameters), and registered to bus, you will receive the ProductsListResponse object.
|
|
Next the important implementation is the IntentService. In this case i created a Service named RestfulQueryService. I will add the important code contents to show the implemenatation.
|
|