How to get started with EventBus in 3 steps

Contents

The EventBus API is as easy as 1-2-3.

Before we get started make sure to add EventBus as a dependency to your project.

Step 1: Define events

Events are POJO (plain old Java object) without any specific requirements.

Step 2: Prepare subscribers

Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the @Subscribe annotation.
Note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).

Subscribers also need to register themselves to and unregister from the bus. Only while subscribers are registered, they will receive events. In Android, in activities and fragments you should usually register according to their life cycle. For most cases onStart/onStop works fine:

Step 3: Post events

Post an event from any part of your code. All currently registered subscribers matching the event type will receive it.

Learn more

Have a look at the full documentation to learn about all features of EventBus.

Spread the love