Step 1: Define events

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

Java

1

2

3

4

5

6

7

8

publicclassMessageEvent{

publicfinalStringmessage;

publicMessageEvent(Stringmessage){

this.message=message;

}

}

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).

Java

1

2

3

4

5

6

7

8

9

10

11

// This method will be called when a MessageEvent is posted (in the UI thread for Toast)

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:

Java

1

2

3

4

5

6

7

8

9

10

11

@Override

publicvoidonStart(){

super.onStart();

EventBus.getDefault().register(this);

}

@Override

publicvoidonStop(){

EventBus.getDefault().unregister(this);

super.onStop();

}

Step 3: Post events

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