Guava: Event Bus Eventbus

Source: Internet
Author: User
Tags eventbus

Eventbus literal translation is the event bus, which uses the publish-subscribe mode to support communication between components, do not need to explicitly register callbacks, more flexible than the observer mode, can be used to replace the traditional Java event listening mode, Eventbus is decoupled, it is not a generic publish subscription system, Nor can it be used for interprocess communication. There are several Eventbus libraries available for Android: Google's Guava,guava is a huge library, and Eventbus is just a small feature that comes with it, so it's not much used in real-world projects. The most used is greenrobot/eventbus, the advantages of this library is simple interface, integration is convenient, but the method name is limited, does not support annotations. Another library Square/otto modified since guava, with a lot of people.

Taking Greenrobot/eventbus as an example, let's take a look at typical uses of the Eventbus pattern:

Register Eventbus, accept event class Fragment {public    void OnCreate () {       eventbus.getdefault (). Register (this);    }    public void OnDestroy () {       eventbus.getdefault (). Unregister (this);    }    public void OnEvent (SomeEvent1 event) {        ///handle event    }}//Processing task, sending events public class Service {public    void Dosom Ething () {        //do your work        //Send event        Eventbus.getdefault (). Post (New SomeEvent1 ());    

A few questions about the Eventbus?

    1. event definition : Any object can be;
    2. event handler Registration : Event handling method, add annotations, and then the event handler object is registered to the bus, the bus maintains an event and event handler association relationship, in memory;
    3. handling of events : Synchronous processing and asynchronous processing, event queuing is maintained in local cache, synchronous way directly to the current thread to execute, asynchronous processing strategy is to initialize the event bus at the time of a thread pool out, by the thread pools to execute asynchronously;
    4. Eventbus opened three methods , Register/post/unregister
    5. Why is there a unregister ? In the 99.99% usage scenario, it is not going to register/unregister some observer at runtime, in the spring environment, but also in Init register/unregister. However, this 0.01% usage scenario must be considered in the framework.

First, guava Eventbus observer pattern

First, we declare a observer:

public class Eventobserver {  @Subscribe public void onMessage (Message message) {    ...  }}

This class does not inherit any interfaces, but declares a @subscribe on the method used to respond to the notification.

Using Eventbus is simple, first declare one:

Eventbus Eventbus = new Eventbus ();

Then, register our well-written observer:

Eventbus.register (New Eventobserver ());

When you want to notify Observer, we just need to:

Eventbus.post (message);

Here, we do not tell Eventbus that we are dealing with a type of message, except that this type is used on the interface declaration of the Eventobserver OnMessage method. However, when we send the message out, it matches the type to ensure that our message is correctly sent to the corresponding place.

This implementation is simpler than the original implementation of the JDK. Eventobserver no longer needs to exist in an inheritance system, and inheritance is always a yoke that puts us in a system:

    • We don't have to follow a specific name, like Observer's update, and the name OnMessage here is our own.
    • We do not have to follow a particular type, such as an object that is observable and as a parameter in the Update method, but rather a type chosen according to our own requirements.

This transformation allows the statically typed Java language to have some dynamic type traits, and also makes the program more flexible. This flexibility is largely due to annotation, which largely affects the Java program design style.

In addition to the standard Eventbus,guava also provides another asynceventbus, from the name can be seen, this is an asynchronous Eventbus, that is, after the message is thrown to it, will immediately return, as for the observer when processing, that is its thing. When processing time-consuming processing is useful, we rely on executors to implement the asynchronous event bus.

Asynceventbus Eventbus = new Asynceventbus ("Test", Executors.newcachedthreadpool ());

In addition: for the use of Eventbus see also: http://blog.mcxiaoke.com/2015/08/03/how-to-write-an-eventbus-part1/

Ii. examples

1, the definition of an event (any object can be an event)

public class SignEvent {        private String companyName;     Private String signname;        Private Date signdate;     Public SignEvent (String name,string signname, Date signdate) {         super ();         This.companyname = name;         This.signname = Signname;         This.signdate = signdate;     }       Public String GetMessage () {         StringBuilder sb = new StringBuilder ();         Sb.append ("logistics company:"). Append (this.companyname);         Sb.append ("Recipient:"). Append (Signname). Append (", Receipt Date:"). Append (signdate);         return sb.tostring ();     } }

2, define two event listeners, add annotations to do event subscriptions

public class Ytoeventlistener {@Subscribe public void consign (SignEvent si Gnevent) {if (Signevent.getcompanyname (). Equalsignorecase ("Yto")) {System.out.println ("Yto ...             Start shipping ");         System.out.println (Signevent.getmessage ()); }} @Subscribe public void delivery (SignEvent signevent) {if (Signevent.getcompanyname (). equalsign Orecase ("Yto")) {System.out.println ("Yto ...         Start delivery "); }}} public class Sfeventlistener {@Subscribe public void consign (SignEvent signevent) {if (Signeven T.getcompanyname (). Equalsignorecase ("SF")) {System.out.println ("SF ...             Start shipping ");         System.out.println (Signevent.getmessage ()); }} @Subscribe public void delivery (SignEvent signevent) {if (Signevent.getcompanyname (). Equalsignore Case ("SF")) {System.out.println ("SF ...         Start delivery "); }     } } 

Examples of  3, Eventbus, including time registrations, and the submission of events

public class Eventbustest {public static void Siginalthreadconsumer () {Eventbus bus = new Eventbus ("Iamzhon                Gyong ");         Sfeventlistener SF = new Sfeventlistener ();         Ytoeventlistener yto = new Ytoeventlistener ();         Bus.register (SF);              Bus.register (Yto);         SignEvent sign1 = new SignEvent ("SF", "more than Bear", New Date ());                Bus.post (SIGN1);         SignEvent sign2 = new SignEvent ("Yto", "Your Sister's", New Date ());        Bus.post (SIGN2);              public static void Multithread () {Eventbus bus = new Asynceventbus (Executors.newfixedthreadpool (3));         Sfeventlistener SF = new Sfeventlistener ();         Ytoeventlistener yto = new Ytoeventlistener ();         Bus.register (SF);         Bus.register (Yto);         SignEvent sign1 = new SignEvent ("SF", "more than Bear", New Date ());                Bus.post (SIGN1);         SignEvent sign2 = new SignEvent ("Yto", "Your Sister's", New Date ());        Bus.post (SIGN2); } public static voidMain (string[] args) {eventbustest.siginalthreadconsumer ();     Eventbustest.multithread (); } }

Guava: Event Bus Eventbus

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.