Dispatches events to listeners, and provides ways for listeners to register themselves.
The Bus allows publish-subscribe-style communication between components without requiring the components to
explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace
traditional Android in-process event distribution using explicit registration or listeners. It is not a
general-purpose publish-subscribe system, nor is it intended for interprocess communication.
Receiving Events
To receive events, an object should:
- Expose a public method, known as the event handler, which accepts a single argument of the type of event
desired;
- Mark it with a
com.squareup.otto.Subscribe annotation;
- Pass itself to an Bus instance's
#register(Object) method.
Posting Events
To post an event, simply provide the event object to the
#post(Object) method. The Bus instance will
determine the type of event and route it to all registered listeners.
Events are routed based on their type — an event will be delivered to any handler for any type to which the
event is assignable. This includes implemented interfaces, all superclasses, and all interfaces implemented
by superclasses.
When
post is called, all registered handlers for an event are run in sequence, so handlers should be
reasonably quick. If an event may trigger an extended process (such as a database load), spawn a thread or queue it
for later.
Handler Methods
Event handler methods must accept only one argument: the event.
Handlers should not, in general, throw. If they do, the Bus will wrap the exception and
re-throw it.
The Bus by default enforces that all interactions occur on the main thread. You can provide an alternate
enforcement by passing a
ThreadEnforcer to the constructor.
Producer Methods
Producer methods should accept no arguments and return their event type. When a subscriber is registered for a type
that a producer is also already registered for, the subscriber will be called with the return value from the
producer.
Dead Events
If an event is posted, but no registered handlers can accept it, it is considered "dead." To give the system a
second chance to handle dead events, they are wrapped in an instance of
com.squareup.otto.DeadEvent and
reposted.
This class is safe for concurrent use.