Communication Within an Android App With EventBus

Communication Within an Android App With EventBus

A typical Android app tends to be composed of many layers, modules or structures such as Fragments, Activities, Presenters, and Services. Effective communication between these components can become difficult if they are tightly coupled together.

In the lower level of your app architecture, such as the database, when an action happens, you might want to send data to a higher level such as the view. To do this, you might want to create a listener interface, async tasks or callbacks. All of these will work, but they have some major drawbacks:

  • direct or tight coupling
  • registering and unregistering multiple dependencies individually
  • repetition of code
  • difficulty in testing
  • increased risk of bugs

Using publish/subscribe or message bus architecture prevents all the potential problems highlighted above. It is a very good way to implement effective communications between components in an application without any of them needing to be aware of the others immediately. Using publish/subscribe in Android, any app component can publish events which it will hand over to the bus, and the relevant consumers can consume or subscribe to them.

To use greenrobot EventBus, you need to first add it to in the app module build.gradle file, include compile 'org.greenrobot:eventbus:3.0.0', and then sync your project afterwards.

A subscriber simply subscribes to an event by registering in the event bus and can also unregister that event. To be a subscriber, you have to do three main things:

1. Register the subscriber in the event bus with register(). This informs the event bus that you want to begin receiving events. In an activity, this is in the onStart() method, while in a fragment put this in the onAttact(Activity activity) method.

Continue reading at Tuts+

SHARE ON