Skip to content

EventBus for Android in 4 Easy Steps

If you’ve read my Top 10 Essential Android Developer Libraries 2019, you might have noticed EventBus, and this one library does seem to gather a little controversy. In case you’re completely new to it, EventBus lets you broadcast events that can be heard anywhere within your app, as long as those activities/fragments have an “EventBus” registered. Some say it’s great for decoupling and keeping your app modular, while others say it completely breaks the rules of MVP architecture.

It’s popularity does prove it has its uses though, as EventBus is used by the likes of Tinder, Pinterest, and PayPal (source be here). In any case, I think it could be a great addition to the developer’s toolbelt in the case that calling an event would traditionally garner unneeded complex logic, and is great for keeping your event senders and receivers decoupled.

Import the Dependency

Add this to your app/build.gradle file.

implementation 'org.greenrobot:eventbus:3.1.1'

Step 1: Define Event Class

An event should be a classic POJO.

class FishFoundEvent(val fish: String)

Step 2: Register EventBus

In your activity/fragment, register and unregister EventBus in the appropriate lifecycle event (usually onStart/onStop) accordingly so that it can listen for events.

override fun onStart() {
    super.onStart()
    EventBus.getDefault().register(this)
}

override fun onStop() {
    super.onStop()
    EventBus.getDefault().unregister(this)
}

Step 3: Add Subscriber Methods

These are the methods that define what happens when an event is received, identified by the @Subscribe annotation (you can optionally define a Thread the subscriber method is called in).

@Subscribe(threadMode = ThreadMode.MAIN)
fun onFishFoundEvent(event: FishFoundEvent) {
    Toast.makeText(this, event.fish, Toast.LENGTH_SHORT).show()
}

Step 4: Post Events

Post from anywhere in your code, and any registered subscribers to the same event type will receive it.

EventBus.getDefault().post(FishFoundEvent("Salmon"))

 

Tags: