EventBus is an opensource library for android publish/subscribe event bus for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code simplifying the code.
Event Bus Features:
- Convenient Annotation based API: Convenient Annotation based API: Simply put the @Subscribe annotation to your subscriber methods. Because of a build time indexing of annotations, EventBus does not need to do annotation reflection during your app’s run time.
- Android main thread delivery: When interacting with the UI, EventBus can deliver events in the main thread regardless how an event was posted.
- Background thread delivery: If your subscriber does long running tasks, EventBus can also use background threads to avoid UI blocking.
- Event & Subscriber inheritance: In EventBus, the object oriented paradigm apply to event and subscriber classes. Let’s say event class A is the superclass of B. Posted events of type B will also be posted to subscribers interested in A. Similarly the inheritance of subscriber classes are considered.
- Jump start:You can get started immediately – without the need to configure anything – using a default EventBus instance available from anywhere in your code.
- Configurable: To tweak EventBus to your requirements, you can adjust its behavior using the builder pattern.
Add Dependency in your project build.gradle
1 |
implementation 'org.greenrobot:eventbus:3.1.1' |
Create Global instance of EventBus so we can create instance EventBus:
1 2 3 |
object GlobalEventBus { val eventBus: EventBus? = EventBus.getDefault() } |
To Post data using Event Bus :
1 2 |
val event: String = Events.StringData("Hello World").message GlobalEventBus.eventBus!!.post(event) |
Register Event Bus in Activity onStart() method:
1 2 3 4 |
override fun onStart() { super.onStart() GlobalEventBus.eventBus!!.register(this) } |
Unregister-Event Bus in Activity onStop() method:
1 2 3 4 |
override fun onStop() { super.onStop() GlobalEventBus.eventBus!!.unregister(this) } |
To receive the post data we need to subscribe the MessageEvent:
1 2 3 4 |
@Subscribe fun getMessageEvent(message: String) { Toast.makeText(this,message,Toast.LENGTH_LONG).show() } |
@Subscribe annotation here specifies that the below function will execute taking the single parameter of type CustomEvent.
Event Bus is the very tiny library, it is so helpful to reduce boilerplate code and for creating a decoupled system.