Android--otto Event Bus--the use of communication framework between components--mode parsing

Source: Internet
Author: User
Preface: Otto Event Bus-the communication framework between components for the previous situation between the activity or fragment between the jump value is generally used bundle, intent, etc., from Activitya--- Activityb with StartActivity, with Startactivityforresult () can accept the latter to the former parameters and can do some updates UI and other operations. This is to determine which of the buttons from a jumps to B, set a unique identifier to define what frist=1,fffff=2 and so on. The Otto event bus solves this problem, as long as the recipient accepts the subscription at the subscription event, and the value type is uniquely labeled. This way, as long as the post is triggered, the receiver executes the specified method, even if it is not returned to the a interface can be executed. Reasons for using the Otto event bus framework
    1. In general, the transfer of values between activity and activity in Android, we pass the intent way;
    2. Between activity and fragment we pass setarguments, value callback we are in Fragment Onattach () interface way implementation;
    3. We usually use the binder mechanism between activity and service, but the binder mechanism actually uses the interface callback method;
    4. In some more complex situations, such as when the activity nested multiple fragment pages, if the value of a page has changed, the other pages will follow the update operation of the data, so we will use the interface callback frequently, this way is too high coupling.
The mode of the Otto event

For such a convenient framework, the addition of Java mode is necessary, whether it is RXJAVA (Observer mode extension) or Eventbus have Observer mode , so the middle of the mode.

A simple use of
    • @Subscribe:这个在调用了register后有效,表示订阅了一个事件,并且方法的用 public 修饰的.方法名可以随意取,重点是参数,它是根据你的参数进行判断
    • @Produce注解告诉Bus该函数是一个事件产生者,产生的事件类型为该函数的返回值。
1-1: Add Dependency
Dependencies {  ' com.squareup:otto:1.3.8 '} or //Otto event bus    compile ' Com.squareup:otto:+ '
1-2: Subscribe and unsubscribe
Bus.register (This), Bus.unregister (this); Release: (new   Public The . Method name can be arbitrarily taken, the emphasis is on parameters, it is based on your parameters to Judge @produce note tells the bus that the function is an event creator, the resulting event type is the return value of the function. Finally, Proguard needs to do some extra work to prevent confusion:class * {    public *;       public *;}
1-3:otto recommends using a singleton mode to ensure that only one instance
 Public classBusproviderextendsBus {/*** Returns a unique bus object through singleton mode, and overrides the parent class's Post method, which can be called by any thread through handler implementation*/    PrivateHandler Mhandler =NewHandler (Looper.getmainlooper ()); Private StaticBus bus =NewBusprovider (); PrivateBusprovider () {} Public StaticBus getinstance () {returnbus; } @Override Public voidPostFinalObject Event) {        if(Looper.mylooper () = =Looper.getmainlooper ()) {            Super. Post (event); }Else{ (NewRunnable () {@Override Public voidrun () {Busprovider.Super. Post (event);        }            }); }    }}
1-4: Call A-->b @SubscribeActivitya:
/*** Created by Liuzhi Pass on 2018/7/4.*/ Public classOttotestoneextendsappcompatactivity {Privatebus bus; PrivateButton Button,button2; @Overrideprotected voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);         Setcontentview (r.layout.ottotwo_layout); //SubscribeBus =busprovider.getinstance (); Bus.register ( This); Button=Findviewbyid (; Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (Ottotestone. This, Ottotesttwo.class);            StartActivity (Intent);    }        }); }//annotations Receive string Types@Subscribe Public voidSetText (String textstring) {button.settext (textstring); LOG.E ("Detection 1", textstring+ ""); }//Receive Bean Type@Subscribe Public voidsetText2 (Editbean textstring) {Button2.settext (textstring.getedit1 ()+""+textstring.getedit2 ()); LOG.E ("Detection 2", textstring.getedit1 () + "" +textstring.getedit2 ()); }    /*** Unsubscribe **/@Overrideprotected voidOnDestroy () {busprovider.getinstance (). Unregister ( This); Super. OnDestroy (); }}

/*** Created by Liuzhi Pass on 2018/7/4.*/ Public classOttotesttwoextendsappcompatactivity {Privatebus bus; @Overrideprotected voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Get InstanceBus =busprovider.getinstance (); //RegisterBus.register ( This);        Setcontentview (r.layout.ottoone_layout); Button Button=Findviewbyid (R.ID.ID_BTN); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {/*Send , here is the bean, you can send the string type of data directly, receive is a string type of receive. */Editbean Editbean=NewEditbean (); Editbean.setedit1 ("Ni"); Editbean.setedit2 ("Hao"); Editbean.settotal ("Ma");   (Editbean);    }        }); }}

As soon as there is activity or fragment jumps to the page, the event is automatically generated, and then the data is updated at the Subscriber (who subscribes to who has changed).

       //Get InstanceBus =busprovider.getinstance (); //RegisterBus.register ( This);    Setcontentview (r.layout.ottothird_layout); } @Produce PublicEditbean providerevent () {Editbean eventData=NewEditbean (); Eventdata.setedit1 ("Hello World"); returnEventData; } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Bus.unregister ( This); }
Note: A->b in the @Produce mode is the event in a, that is, the so-called event creator, when a jump from A to B, if there is a editbean in B, it will directly touch a @produce method, and update some of the data, which compared to post, It's a bit simple, because you don't have to do any more, the previous interface has been updated, but post can control when the event is launched, the button is clicked, or the network request succeeds directly ("... Second, the Observer pattern the Foreword observer pattern (sometimes referred to as model-view mode, source-listener (Listener) mode, or slave mode) is one of the software design patterns. In this mode, a target object manages all the observer objects that are dependent on it and proactively notifies when its own state changes. This is usually done by calling the methods provided by each observer. This pattern is often used to implement an event-handling system. Note: When implementing the observer pattern, it is important to note that the interaction between the observer and the observed object does not reflect a direct call between the classes, otherwise it will tightly couple the observer and the observed object, fundamentally violating the principle of object-oriented design. Neither the Observer "observes" the object of observation, nor the observer notifies the observer of its own change, should not be called directly. The Observer (OBSERVER) registers itself in the observed object (Subject), and the observed object stores the observer in a container (Container). The observed object has undergone some change, getting all registered observers from the container and notifying the observer of the change. The observer is told to dismiss the observation and the observer removes the observer from the container. When the observer registers himself in the viewer's container, the observer should not ask about the observer's specific type, but should use the observer's interface. The advantage is that there are other observers in the program, so long as the observer is the same interface implementation. A observed person can correspond to multiple observers, and when the observer changes, he can notify all the observers of the message. interface-based rather than specific implementations-this provides greater flexibility for the program.


This creates an abstract observer (OBSERVER) and an observer (Subject), then inherits the abstract observer, who changes itself by observing the observed (Subject).

To create a class:
    • Abstract Observer (Observer)
    • Observed (Subject)
2-1: The observed person
 Public classSubject {PrivateList<observer>observers=NewArraylist<observer>(); PrivateObserver Observer; Private intState ; //Change Situation     Public intgetState () {returnState ; }     Public voidSetState (intState ) {         This. State =State ; }    //binding     Public voidbinding (Observer Observer) {observers.add (Observer); }    /*** UNBINDING (logoff observer, sometimes not available to instance) **/     Public voidunbinding (Observer cls) {if(CLS = =NULL)Throw NewNullPointerException ();          Observers.remove (CLS); }    //Notice     Public voidnotifyallobservers () { for(Observer observer:observers) {observer.update (); }    }}

It is important to note that if the regular collection is not directly with remove, the following conversions are removed.

  iterator<observer> Iterator = Observers.iterator ();

2-2: The Observer (Observer)
/***/publicabstractclass  Observer    {protected  Subject Subject;      Public Abstract void update ();}
2-3: Inheritance Observer

It is important to note that I have created 3 of the following classes, with only one pasted, Firstobserver,secondobserver,thirdobserver.

 Public class extends Observer {    public  firstobserver (Subject Subject) {        this. Subject=  Subject;        Subject.binding (this); // binding     }    @Override    publicvoid  update () {        // used to update data        System.out.println ("I am the first Observer:" +subject.getstate ());}    }

2-4: Test

In the main method main here is the binding in the constructor method of each subclass, so as long as the creation of the object is already bound, unordered binding again, of course, can also be unbound.

// load the observed person        New Subject ();         // Load Observer        New Firstobserver (subject);         New Secondobserver (subject);         New Thirdobserver (subject);        Subject.setstate (2);        Subject.notifyallobservers ();

subject.unbinding (secondobserver);        Subject.setstate (3);        Subject.notifyallobservers ();

Related Article

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: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: