Search code examples
javaandroidandroid-fragmentsbroadcastreceiverevent-bus

Call Method to initiate code or use event bus


I'm using Broadcast Receivers to send data around to activities and fragments. That data is either primarily for information/display purposes or to activate some code in the fragment/activity.

What are the advantages/disadvantages of using an event bus to get data directly into a fragment vs just hitting a method in the fragment from the host activity to send data/activate code?

This is the non-event bus way....

 public class loqooBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
           if (intent.getAction().equals("tv.SCENE")) {
             try {
                message = (JSONObject) 
                   new JSONTokener(intent.getStringExtra("message")).nextValue();
                sceneId = message.getString("scene_sceneid");
                if (sceneId == lastSceneId){
                    return;
                }
                channel = message.getString("channel");
                args.putString("json", message.toString());
            } catch (JSONException e) {

            }
            lastSceneId = sceneId;
            pushToFeedFromActivity(message);
      }

intent is coming in from a service, which is just a json message, coming from outside.

Should I send the message from the service via event bus to its intended destination (fragments) or leave all well alone?


Solution

  • I'm currently using Otto in a not-so-small application, and I must say it's cool. The project has different build types and flavours, and some use cases can be solved really elegantly - e.g. processing events differently in Debug and Production builds (by having different subscribers).

    That's a huge plus for using events / an eventbus.

    On the downside everything's pretty decoupled. While this might sound like a argument for eventbus, it's actually not always the case. It's pretty easy to make the program flow jump around seemingly randomly, and debugging can become a real pain in the neck. Refactoring is another issue - that's potentially not as straight forward as it would be without events floating around.

    My advice: Use it, but don't overuse it. If there's a straight forward way for two collaborators to communicate prefer that. But don't decouple things that actually belong together.