8. EventBus in 4 Steps
1. Define an event
public class MyEvent {}
2. Register subscriber
EventBus.getDefault().register(this);
3. Post an event
EventBus.getDefault().post(event);
4. Receive the event
public void onEvent(MyEvent event);
10. • EventBus instances
• It anywhere in your code
• Event handler methods
• Naming convention: onEvent
• public visibility
• No return value (void)
• Single parameter for the event to receive
11. Event Type is a Filter
Publisher
Event
Bus
Subscriber
Event
post
(MyEvent)
Event
onEvent(MyEvent)
Subscriber
onEvent(OtherEvent)
19. Event class
public class ItemSelectedEvent {
public final Item item;
public ItemSelectedEvent(Item item) {
this.item = item;
}
}
20. Post / Receive
// In ListFragment
EventBus.getDefault().post(new ItemSelectedEvent(item));
// In DetailFragment (extends EventBusFragment)
public void onEvent(ItemSelectedEvent event) {
…
}
21. Thread Modes
• PostThread: Direct call in same thread
• MainThread: UI updates etc.
• BackgroundThread: „not the main thread“
• Async: always asynchronous to posting
• Used in the method name: onEventXXX
• No additional code required
23. Sticky Event
• Events can be posted using sticky mode
postSticky(event); // Instead of post(…)
• The last sticky event is kept in memory
• Registration with getting sticky events
registerSticky(subscriber);
• Query for sticky event
getStickyEvent(Class<?> eventType)
• Remove sticky event (Class or Object)
removeStickyEvent(Class<?> eventType)
24. When to use EventBus
• Medium/high distance of components:
• Potentially multiple dependencies
• Asynchronous logic
• When not to use EventBus
• Strictly internal matters:
• Use methods and interfaces instead
• Inter-process communication