Android Event Bus Implementations using Otto

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
dependencies {
  compile 'com.squareup:otto:1.3.6'
}


Create BusProvider class to initiate the Event Bus
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;

/**
 * Created by Dulan Dissanayake on 2/16/2015.
 */
public final class BusProvider {
    private static final Bus BUS = new Bus(ThreadEnforcer.ANY);

    public static Bus getInstance() {
        return BUS;
    }

    private BusProvider() {
    }
}


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.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().startService(createRequestIntent());
}
private Intent createRequestIntent(){
        final Intent intent = new Intent(getActivity(), RestfulQueryService.class);
        intent.putExtra("url",createProductsUrl());
        intent.putExtra("type",Constants.REQUEST_TYPE_PRODUCTS_LIST);
        intent.putExtra("method", "GET");

        return intent;
    }

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.

@Subscribe
public void getProductsList(ProductsListResponse productsResponses){
        
//Do anything with the response 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.

@Override
protected void onHandleIntent(Intent intent) {
  String url = intent.getStringExtra("url");
  String type = intent.getStringExtra("type");
  String requestMethod = intent.getStringExtra("method");

  //Do the server requests and create the response object

  ProductsListResponse responseObject = ... 
  //Object can be created from a json string using Gson

  BusProvider.getInstance().post(responseObject);
  
}

Comments

Popular posts from this blog

SSL Pinning in Android

Java Unit testing using JUnit @RunWith(Suite.class)