What is Event Bus
- An event bus is a software design pattern that facilitates communication and coordination between different parts of a software system or application.
- It provides a mechanism for components or modules within the system to communicate without needing to have direct references or dependencies on each other.
- They can publish events or messages to the event bus, and other components can subscribe to listen for specific types of events they are interested in.
Concept of Event Bus
-
Publishing Events: Components or modules can publish custom-defined events to the event bus when specific actions or events occur.
-
Subscribing to Events: Other components or modules can subscribe to the event bus in specific types of events. They provide callback methods or handlers that should be invoked when those events are published.
-
Decoupling: Event buses promote loose coupling between components which makes the system more modular, maintainable, and extensible.
-
Asynchronous Communication: Event buses often support asynchronous communication, i.e events can be published and consumed on different threads or at different times without blocking the main execution thread.
-
Event Propagation: The event bus is responsible for delivering events to the appropriate subscribers based on their subscriptions and manages the routing and delivery of events.
-
Event Handling: Subscribers typically define event handlers or callback methods when specific event occur and perform actions, update state, or trigger further processing.
Event bus libraries available for Android development, such as:
-
GreenRobot’s EventBus: A widely used open-source library for implementing the event bus pattern in Android.
-
Otto: Another popular event bus library, developed by Square, which offers similar functionality to EventBus.
-
RxJava: While not strictly an event bus library, RxJava can be used to implement event bus-like functionality using its observables and subscribers.
Extra Pinch with Event Bus in Android
With the introduction of Android Architecture Components and ViewModel pattern, LiveData and ViewModel both are used to handle communication between components.
However, event buses are still a choice for certain use cases, especially when dealing with legacy code or when a more flexible event-driven architecture is preferred.
Usage of Event Bus in Android
We use EventBus because
- simplifies the communication between components
- decouples event senders and receivers
- performs well with Activities, Fragments, and background threads
- avoids complex and error-prone dependencies and life cycle issues
- makes the code simpler, fast
- is tiny (~60k jar)
USAGE ~
Step 1 : Add Event Bus dependency in app/build.gradle
implementation 'org.greenrobot:eventbus:3.2.0'
Step 2 : Create event classes that represent the events you want to send and receive. These classes should contain any relevant data that you want to pass with the events.
public class MessageEvent {
private String message;
public MessageEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Step 3 : Register and Unregister Subscribers
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this); // Register as a subscriber
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this); // Unregister when the component is no longer active
}
Step 4 : Subscribe to Events
@Subscribe
public void onMessageEvent(MessageEvent event) {
// Handle the received message event
String message = event.getMessage();
// Update your UI or perform other actions
}
Step 5:
public class MainActivity extends AppCompatActivity {
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this); // Register as a subscriber
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this); // Unregister when the component is no longer active
}
@Subscribe
public void onMessageEvent(MessageEvent event) {
// This method will be called when a MessageEvent is posted on the event bus
String message = event.getMessage();
// Do something with the message
}
// ...
}
Step 6 : Post Events
EventBus.getDefault().post(new MessageEvent("Hello, Earth!"));
This line posts a MessageEvent to EventBus with the message “Hello, Earth!“.
Step 7 : Receive and Handle Events
-
When you post an event, EventBus will deliver it to all registered subscribers with matching event handler methods.
-
In this example, the onMessageEvent method in the activity will be called with the MessageEvent, and you can handle the event there.
Step 8: Handle Thread Considerations
- EventBus allows you to specify on which thread the event handling should occur by annotating your subscriber methods with
@Subscribe(threadMode = ThreadMode.X)
- Common thread modes include ThreadMode.MAIN for the main (UI) thread and ThreadMode.BACKGROUND for a background thread.
One needs to be careful of thread synchronization when updating UI elements from background threads.
For example, please follow the link : https://github.com/greenrobot-team/greenrobot-examples/tree/master/eventbus-kotlin/app/src/main/java/com/example/eventbuskotlin
Drawbacks of Event Bus in Android
-
Complexity and Readability: As the application grows, the use of event buses can lead to a more complex codebase and challenging to trace the flow of events, especially when multiple components are interacting via the event bus which can negatively impact code readability and maintainability.
-
Global Event Bus: Event buses are often implemented as a global singleton. Any component can publish and subscribe to events, potentially creating unexpected interactions and making it difficult to track where events originate.
-
Memory Leaks: If subscribers are not properly unregistered from the event bus when they are no longer needed (e.g., in the onStop or onDestroy methods), it can lead to memory leaks, as the event bus may still hold references to these objects.
-
Lack of Type Safety: Event buses typically rely on sending objects as events which can lead to a lack of type safety, making it possible for subscribers to receive events that they don’t expect or know how to handle.
-
Performance Overhead: While the performance overhead of event buses is generally low, it’s still an additional layer of indirection.
Summary
That’s a basic overview of how to use EventBus in Android. It simplifies communication between components by using a publish-subscribe mechanism. It is required to register and unregister the subscribers to prevent memory leaks and to follow best practices for event-driven architecture in the Android application.
This library itself stopped maintenance 1 or 2 years back, but in some projects developers use this