You are facing difficulty in changing one part of the system without impacting another area. EventBus was introduced to solve this problem. It includes notifying activities or fragments when tasks are completed, such as when an AsyncTask or a background service is over.
An EventBus offers you the opportunity to work with just a few lines of code—simplified code, removing dependencies, and a fast development process. Do you know how to make a basic Android EventBus?
This blog will make you learn everything about the EventBus in Android.
At the base level of your application architecture, such as a database, when a specific event occurs, you might think about sending data to other components such as the view. To implement this, you will be required to create a listener interface, async tasks or callbacks. These methods not bad, but they have some obnoxious drawbacks:
1. Straight or binded coupling
2. Recording and removing diverse dependencies individually
3. Code repetition
4. Testing difficulties
5. Increased probability of bugs
Using publish/subscribe or message bus architecture prevents all the possible problems highlighted above. In fact, it eases effective communication in an application without any of the sub-elements needing to be aware of each other immediately. With the use of publish&subscribe in Android, any app component can publish events which will be passed on to the bus, and the relevant consumers can consume or subscribe to them.
Sounds exciting right? Now let’s have a look into it in detail
To integrate green robot EventBus, you need to first add it to the app module of your build.gradle file, so simply add this dependency:
include compile 'org.greenrobot:event bus:3.0.0', and then sync your project later on after adding a dependency.
The role of the subscriber is to simply subscribe to an event by registering in the event bus and can also unregister that particular event. First, to implement subscription, you have to do three main things:
1. You can register the subscriber in the event bus with register(). This will inform the event bus that you are all set to start receiving events. Whilst in an activity, this is in the onStart() method, however, in case of a fragment put this in the onAttach(Activity activity) method.
2. Now Unregistering the subscriber, tell the event bus to stop sending events. In the activity, this is to be put in the onStop() method, while in a fragment put this in the onDetach() method.
3. To receive an event simply Implement the onEvent() to signify the type of event you want to receive and action to perform when you receive the event. Notice the @Subscribe annotation at the top of this method. In this case, we would like to subscribe to a normal event and not a sticky one—We’ll discuss the difference later.
The events used in green robot EventBus are just any simple objects that you define. You can use a wide range of event classes if you want. They do not require any inheritance of base class or interface—they're basically just POJO (Plain Old Java Objects).
The major difference between post-event and post sticky event is the caching pattern employed inside the event bus. Whenever a person posts a sticky event, this event is reserved in a cache. When a new activity or fragment subscribes to the event bus, it gets the latest sticky event from the cache instead of waiting for it to be fired again to the event bus—so this event stays in the cache even after a subscriber has gotten it.
Sticky events are posted with the post sticky(MessageEvent) method and non-sticky events with the post(MessageEvent) method.
For a regular, non-sticky event, if there no subscriber is found, the event will be thrown away. Event when sticky will be cached, although, in case when a subscriber hops along later.
So when should we use post sticky event? We can do this in case of tracking down the user's location, or for simple caching of data, keep a track of battery levels, etc.
To subscribe to a sticky event, you need to include sticky = true inside the @Subscribe annotation. This signifies that we are ready to receive a sticky event of type MessageEvent from the stored cache.
There are four major thread modes available for subscribers to choose from: posting, main, background, and async.
@Subscribe(threadMode = ThreadMode.POSTING)
This is the default. Subscribers will be invoked in the same thread as the thread where the event is on. Including ThreadMode.POSTING in your @Subscribe annotation is optional.
@Subscribe(threadMode = ThreadMode.MAIN)
In this thread mode, events will be received by subscribers in the main UI thread, no matter where the event was posted. This is the threaded mode is best suitable in case of updating UI elements as a result of the event.
@Subscribe(threadMode = ThreadMode.BACKGROUND)
Pertaining to this thread mode, events will be received in the same thread where they are posted, just like for ThreadMode.POSTING. The main contrast is that if the event is sent in the main thread, then subscribers will, on the other hand, get them on a background thread. This ensures that event handling doesn't block the app's UI. Still, stay away from running an operation that will take a long time on this thread.
@Subscribe(threadMode = ThreadMode.ASYNC)
In this mode, subscribers will be always receiving events freely from both the current thread and the main thread. This facilitates the subscribers to run on a diverse thread. This is utilizing for long-running operations such as network operations.
In case you want to change the order of receiving the events, then you need to set their priority levels at the time of registration. Subscribers with a higher priority get the event before subscribers having a lower priority. This only leaves an effect on subscribers in the same thread mode. Note that the default priority is always 0.
In case you need to prevent an event from being delivered to other subscribers, call the cancelEventDelivery(Object event) method within the subscriber's event handling method.
For More Details, you can visit the official docs of event bus at:
https://github.com/greenrobot/EventBus
The Event Bus is useful for reactive programming and it leverages events that are more important in application development. It will make your application's features easy to understand for users. Therefore, try to learn and start developing applications with this library.
CTO of Vasundhara Infotech, a leading Software development company in the USA. His technological interests has helped the company in making useful decisions.
Sign Up to our newsletter to get latest updates staight in your inbox.
Vasundhara respects your privancy. No Spam!
Sign Up to our newsletter to get latest updates staight in your inbox.
Vasundhara respects your privancy. No Spam!