Event bus Eventbus mode overview without using the event bus: in multiple places in your app, controls often need to update what they display based on a state. The common solution to this scenario is to define an interface that needs to be focused on the event's control to implement the interface. The event is then triggered to register/unregister these controls that are of interest to the event. For example, Momo relies on mobile location information to get nearby users, so an interface is defined in the Location Update Manager (Mmlocationmanager) to listen for location-Updated events (Mmlocationlistener):
Interface Mmlocationlistener {void onlocationchanged (location location);}
Then implement the above interface in each application where it needs to respond to the event, and then register/unregister the implementation class of the event listener interface in the Location Update Manager (Mmlocationmanager):
Mlocationmanager.get (). Register (this);
The solution above is no problem, but is not the ideal solution. Each control implements this interface, which causes these controls to be strongly coupled with the location manager registration. This also means that when unit testing, you need to simulate (mocked) the location manager to generate location update events.
As application functionality increases, more and more events need to be monitored, and more and more controls need to listen for different events, resulting in more and more controls needing to be registered with the various event managers:
The code begins to become uncontrollable ... mlocationmanager.get (). Register (this); Userauthenticator.get (). Register (this); Settingsmanager.get ( ). Register (this), Syncmanager.get (). Register (this), Configurationmonitor.get (). Register (this);
Registering and cancelling these events will slowly become more and more difficult to manage. It is becoming more and more difficult to test and will lead to inefficient developers, and it is becoming easier to introduce strange bugs in your application.Event Bus Mode-also known as message bus or publisher/Subscriber (Publisher/subscriber) mode-allows two of components to communicate with each other, but they do not know each other.
A component is now registered with the event bus only once, compared to the listener that needs to register the individual events:
Bus.register (this);
The above registration tells event bus that we now want to receive updates for each event. The bus then detects every function in the class with the @subscribe annotation, and invokes the annotated function when the related event occurs.
the position monitoring function in the above example, without implementing the position listener interface and the function inside, only need to provide a function with @subscribe annotation:
@Subscribepublic void LocationChanged (Locationchangedevent event) { //TODO React to location change.}
Now the event bus will send all the locationchangedevent events to the above function.now the Mmlocationmanager class does not have to register the listener, and when the location changes, it is only necessary to post events to the event bus:
Bus.post (New Locationchangedevent (37.892818,-121.772608));
so that the components are decoupled from each other., and unit testing has become simpler.any event can be published to event bus, and event bus will find a function that is interested in the event to invoke。
Note: You may have found that the pattern is also present on Android top-intent system is designed like this!
We can see that after using Eventbus mode, we have simplified several tasks:
- Instead of writing many listener interfaces, use annotations to methods directly.
- Instead of writing a management class for listener registration/unregister, Eventbus is the agreed event bus.
- Do not register or unregister the event. The event bus invokes all methods of interest to it after the event is published.
- The mutual realization of this intermediary communication through the event bus is understood to be decoupled.
In short, you can say that the event bus mode isa solution that provides a unified subscription for events, which is published to achieve communication between components.
subscribers can subscribe to multiple events, and the sender can post any event, and the publisher can also be a subscriber.
Two Eventbus-mode frames in Android:
- Otto is the event bus implementation that the square company uses in their applications. evolved from guava and focused on the Android platform.
- Eventbus is another event bus class library produced by Greenrobot, with a little more functionality. This article will take the Eventbus class library as an example to study.
From a single use view, Eventbus > Otto > Broadcastreceiver (Of course broadcastreceiver as the system's built-in components, there are some features not previously available).
Eventbus is the most concise, Otto most in line with guava Eventbus design ideas, broadcastreceiver the most difficult to use. The first choice is Eventbus.
Android Eventbus Class Library Introduction Eventbus is an event bus class library of Greenrobot's Android system (other square Otto-like) to simplify communication between application components.
When an Android application becomes more functional, it becomes increasingly difficult to ensure efficient communication between the various parts of the application. The **eventbus** is an Android-optimized publish/subscribe messaging bus that simplifies communication between components within an application and between components and background threads. such as requesting the network, and so on when the network returns through the handler or broadcast notification UI, two fragment between the need for listener communication, these requirements can be achieved through **eventbus**.
As a message bus, there are three main elements:
- Event: Events
- Subscriber: Event subscribers, receiving specific events
- Publisher: Event Publisher to notify Subscriber that an event has occurred
Eventbus Features:Not based on annotations and based on Conventions: Event subscription functions are not based on annotations (Annotation), but are based on naming conventions, in Android (especially before 4.0),Annotations are relatively slow to parse. In Eventbus, you use conventions to specify event subscribers for ease of use. That is, all event subscriptions are functions that begin with onevent, specifically, the name of the function is Onevent,oneventmainthread,oneventbackgroundthread,oneventasync four, This is related to Threadmode.
You can send an event anywhere on any thread, call the Eventbus ' post (object) method directly, and instantiate the Eventbus object yourself, but generally use the default singleton as well: ' Eventbus.getdefault () ', The function that subscribes to the corresponding type of event is automatically invoked based on the type of the post function parameter.
Threadmode:As I said earlier, the name of the Subscriber function can only be those 4, because each event subscription function is associated with a ' threadmode ', and Threadmode specifies the function that will be called. The following four Threadmode are available:
Postthread: The handling of the event is in the same process as the sending of the event. The corresponding function name isonEvent。
Mainthread: The handling of the event is performed in the UI thread. The corresponding function name isOneventmainthread。
Backgroundthread: The processing of the event is performed in a background thread, and the corresponding function name isOneventbackgroundthread。 If the thread is a background thread, the event is executed directly, and if the current thread is the UI thread, the event is added to a queue, which is handled by one thread in turn, and if an event is too long, it blocks the dispatch or processing of subsequent events.
the 3 event response functions above should be executed very quickly, otherwise they will block the release of their events.
Async: The corresponding function name isOneventasyncEvent handling is performed in a separate thread, primarily for time-consuming operations in a background thread, with each event opening a thread (the cable pool), but it is best to limit the number of threads. The thread and the publishing thread, the main thread are independent of each other. If the event response function takes a long time to execute, you should use that pattern, such as network access.
Depending on the function name of the event subscription, a different threadmode is used, and the subscriber simply names the function Oneventmainthread if the data is downloaded in the background line loads to be displayed in the UI thread.
Summarize how Threadmode works:
- If it is postthread, direct execution
- If it is mainthread, judge the current thread, and if it is the UI thread that executes directly, join the ' mainthreadposter ' queue
- If it is a background thread, if it is currently the UI thread, join the ' backgroundposter ' queue, otherwise execute directly
- If it is async, join the ' asyncposter ' queue
basic steps to use:
- define the event type: Public class MyEvent {} '
- Define event handling methods: Public void Oneventmainthread '
- Registered Subscribers: Eventbus.getdefault (). Register (This) '
- Send event: Eventbus.getdefault (). Post (New MyEvent ()) '
stickevent:Sometimes an event may be used many times, such as in the previous example of the event bus model article, the latest location update information, may need to be used many times, it is true, you can publish the event as sticky event, and then, when you need to query the information, The latest published event object can be queried through the bus's getstickyevent (classeventtype) function.
Events of the same type save only the most recent event object. The functions for registering and publishing events are Registersticky (...) and Poststicky (Object event), respectively.
Reference: http://blog.chengyunfeng.com/?p=449http://blog.csdn.net/djun100/article/details/23762621
Https://github.com/greenrobot/EventBus/blob/V2.4.0/HOWTO.md
Http://www.cnblogs.com/qianxudetianxia/p/4216949.html
Http://www.cnblogs.com/angeldevil/p/3715934.html
Android inter-component communication framework Eventbus