Sticky Events

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:

Now a new Activity gets started. During registration all sticky subscriber methods will immediately get the previously posted sticky event:

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:

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:

Spread the love