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.
1 2 3 4 5 6 7 8 | public class MessageEvent { 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.
Note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).
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) @Subscribe(threadMode = ThreadMode.MAIN) 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 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:
1 2 3 4 5 6 7 8 9 10 11 | @Override 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.
1 | EventBus.getDefault().post(new MessageEvent("Hello everyone!")); |
Learn more
Have a look at the full documentation to learn about all features of EventBus.