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.
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 5 |
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.
Be the first to comment.