Otto is a powerful, guava-based event bus released by Square that focuses on Android, allowing them to communicate effectively after decoupling different parts of the application.
Open Source project Address: Https://github.com/square/otto
Instruction for use: http://square.github.io/otto/
The following text comes from the official description plus your own experience.
1, using
Create an instance of the event bus:
New Bus ();
Because the bus is the only valid (if it is a shared bus), we recommend getting an instance by injection or other appropriate means. Even with globally unique shared objects
2, Release
Event Publishing is the most important part of bus, and it allows you to tell subscribers that a behavior has occurred. An instance of any class can be posted on a bus bus, and it will only be dispatched to the subscribers type.
To publish a new event, call the method:
Bus.post (new answeravailableevent (42));
Publishing to the bus is a synchronous action, and the program continues execution, which ensures that all subscribers are called.
3,subscribing
A subscription is an event that is released that allows you to be notified that an event has occurred. Subscribe to events, labeling methods and "subscriptions." The method requires only one parameter whose type will you want to subscribe to the event.
Listen to the event published in the previous section we will need the following:
Public void answeravailable (Answeravailableevent event) { // Todo:react to the event somehow!}
The name of the method can be anything you like. Annotations, single parameters, and all requirements for public access.
In order to receive events, an instance of a class needs to be registered with the bus. If this refers to an instance of a class, as the provider of the previous method, we can use the following code to register:
Bus.register (this);
4, the execution of the thread
When you use threads to receive callbacks, sometimes blurry, Otto provides a mandatory mechanism to make sure that you always get the thread you need. By default, all interacting instances are limited to the main thread.
// Both of these is functionally equivalent. New New Bus (Threadenforcer.main);
If you don't care, the interaction of the thread occurs, instantiating a bus instance on the line. If you need additional functionality or validation, you can implement the Threadenforcer interface yourself.