Some events carry information that is of interest after the event is posted. For example, an event signals that some initialization is complete. Or if you have some sensor or location data and you want to hold on the most recent values. Instead of implementing your own caching, you can use sticky events. So EventBus keeps the last sticky event of a certain type in memory. Then the sticky event can be delivered to subscribers or queried explicitly. Thus, you don’t need any special logic to consider already available data.
Sticky Example
Let’s say, a sticky event was posted some time ago:
1 | EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!")); |
Now a new Activity gets started. During registration all sticky subscriber methods will immediately get the previously posted sticky event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } // UI updates must run on MainThread @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onEvent(MessageEvent event) { textField.setText(event.message); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } |
Getting and Removing sticky Events manually
As you saw, the last sticky event gets delivered automatically to matching subscribers when they register. But sometimes it may be more convenient to manually check on sticky events. Also it may be necessary to remove (consume) sticky events so that they won’t be delivered anymore. Example:
1 2 3 4 5 6 7 | MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // "Consume" the sticky event EventBus.getDefault().removeStickyEvent(stickyEvent); // Now do something with it } |
The method removeStickyEvent is overloaded: when you pass in the class, it will return the previously held sticky event. Using this variation, we can improve the previous example:
1 2 3 4 5 | MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // Now do something with it } |