Skip to main content

How to subscribe and unsubscribe to events with EventBus in Kotlin Android

How to subscribe and unsubscribe to events with EventBus in Kotlin Android.

EventBus is an open-source library for Android that simplifies communication between components, such as activities, fragments, and services. It allows you to send and receive events in a decoupled manner, making your code more modular and easier to maintain. In this tutorial, we will learn how to subscribe to events and unsubscribe from them using EventBus in Kotlin Android.

Step 1: Add EventBus Dependency

To get started, you need to add the EventBus dependency to your project. Open your app-level build.gradle file and add the following line to the dependencies block:

implementation 'org.greenrobot:eventbus:3.2.0'

After adding the dependency, sync your project to download the library.

Step 2: Create an Event Class

Before we can subscribe to events, we need to define an event class. An event class represents the data that will be passed between components. Create a new Kotlin file and define a class for your event, for example:

data class MessageEvent(val message: String)

In this example, we have defined a MessageEvent class with a single property message of type String.

Step 3: Subscribe to Events

To subscribe to events, we need to annotate a method with the @Subscribe annotation and register the object containing that method with EventBus. Let's say we have an activity that wants to receive events:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
EventBus.getDefault().register(this)
}

@Subscribe
fun onMessageEvent(event: MessageEvent) {
// Handle the event
textView.text = event.message
}

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

In the onCreate method, we register the activity as a subscriber by calling EventBus.getDefault().register(this). This tells EventBus that the activity is interested in receiving events. The @Subscribe annotation on the onMessageEvent method indicates that this method should be called whenever a MessageEvent is posted.

Inside the onMessageEvent method, we can handle the event as needed. In this example, we set the text of a textView to the message received in the event.

Finally, in the onDestroy method, we unregister the activity as a subscriber by calling EventBus.getDefault().unregister(this). This prevents memory leaks and ensures that the activity will no longer receive events after it is destroyed.

Step 4: Post Events

To send events, we need to create an instance of the event class and post it to EventBus. Let's say we have another component, such as a fragment, that wants to send an event:

class MyFragment : Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

val event = MessageEvent("Hello EventBus!")
EventBus.getDefault().post(event)
}
}

In this example, we create a MessageEvent instance with the desired message and call EventBus.getDefault().post(event) to send the event. EventBus will automatically deliver the event to any subscribers that have registered for it.

Step 5: Unsubscribe from Events

If a component no longer needs to receive events, it should unregister itself as a subscriber to prevent memory leaks. In the previous examples, we already showed how to unregister an activity in the onDestroy method. Similarly, if you have a fragment or any other component, you should unregister it in the appropriate lifecycle method, such as onDestroyView or onStop.

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

It is important to remember to unregister all subscribers to avoid memory leaks.

Conclusion

In this tutorial, we learned how to subscribe and unsubscribe to events using EventBus in Kotlin Android. We added the EventBus dependency, created an event class, subscribed to events in an activity, posted events from a fragment, and finally, unsubscribed from events to prevent memory leaks. EventBus provides a convenient way to decouple components and simplify communication in your Android app.