How to get started with EventBus in 3 steps
EventBus’ API is as easy as 1-2-3. Before we get started with the 3 basic steps, let’s add the EventBus depency to your Gradle script (make sure you are using the latest version):
Step 1: Define events
Events are POJO (plain old Java object) without any specific requirements.
public final String message;
public MessageEvent(String message) {
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. Please note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).
@Subscribe
public void onMessageEvent(MessageEvent event){
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}
// This method will be called when a SomeOtherEvent is posted
@Subscribe
public void handleSomethingElse(SomeOtherEvent event){
doSomethingWith(event);
}
Subscribers also need to register and unregister themselves to the bus. Only while subscribers are registered, they will receive events. In Android, Activities and Fragments usually bind according to their life cycle:
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
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.