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:
Bus.post(new MessageEvent());
annotation
@Subscribe: This is valid after calling register, indicating that an event is subscribed, and the method is publicly decorated. The method name can be taken at will, the key is the parameter, it is judged according to your parameters.

The @Produce annotation tells Bus that the function is an event producer and the type of event generated is the return value of the function.

Finally, proguard needs to do some extra processing to prevent confusion:
-keepattributes *Annotation*
-keepclassmembers class ** {
     @com.squareup.otto.Subscribe public *;
     @com.squareup.otto.Produce public *;
}
1-3:otto recommends using a singleton mode to ensure that only one instance
Public class BusProvider extends Bus {

     /**
      * Return a unique bus object through the singleton mode, and override the parent class's post method, which can be called by the arbitrary thread of the handler.
      */
     Private Handler mHandler = new Handler(Looper.getMainLooper());
     Private static Bus bus = new BusProvider();
    
     Private busProvider(){
        
     }

     Public static Bus getInstance(){
        
         Return bus;
     }
    
     @Override
     Public void post(final Object event) {
         If (Looper.myLooper() == Looper.getMainLooper()) {
             Super.post(event);
         }else {
             mHandler.post(new Runnable() {
                 @Override
                 Public void run() {
                     BusProvider.super.post(event);
                 }
             });
         }
     }
} 
1-4: Call A-->b @SubscribeActivitya:
/**
 * Created by Liu Zhitong on 2018/7/4.
 */

Public class OttoTestOne extends AppCompatActivity {
    Private bus bus;
    Private Button button,button2;
    @Override
    Protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ottotwo_layout);
         //subscription
        Bus = BusProvider.getInstance();
         Bus.register(this);
        Button = findViewById(R.id.id_two);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            Public void onClick(View v) {
                Intent intent=new Intent(OttoTestOne.this,OttoTestTwo.class);
                startActivity(intent);
            }
        });

    }
//Annotation receives String type
    @Subscribe
    Public void setText(String textstring) {
        button.setText(textstring);
        Log.e ("detect 1", textstring+"");
    }
/ / Receive bean type
    @Subscribe
    Public void setText2(EditBean textstring) {
        button2.setText(textstring.getEdit1()+""+textstring.getEdit2());
        Log.e ("detect 2", textstring.getEdit1()+""+textstring.getEdit2());
    }

    /**
     * unsubscribe
     * */
    @Override
    Protected void onDestroy() {
        BusProvider.getInstance().unregister(this);
        super.onDestroy();
    }
} 



ActivityB
/**
  * Created by Liu Zhitong on 2018/7/4.
  */

Public class OttoTestTwo extends AppCompatActivity {

     Private bus bus;

     @Override
     Protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         / / Get an instance
         Bus = BusProvider.getInstance();
         //registered
         Bus.register(this);
         setContentView(R.layout.ottoone_layout);
         Button button=findViewById(R.id.id_btn);

         button.setOnClickListener(new View.OnClickListener() {
             @Override
             Public void onClick(View v) {
                 / * Send, here is the bean, you can also directly send the String type of data, the reception is the String type of A. */
                 EditBean editBean=new EditBean();
                 editBean.setEdit1("ni");
                 editBean.setEdit2(" hao");
                 editBean.setTotal(" ma");
                 Bus.post(editBean);
             }
         });
     }
} 
@Produce


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 an instance
         Bus = BusProvider.getInstance();
         //registered
         Bus.register(this);
         setContentView(R.layout.ottothird_layout);
     }
     @Produce
     Public EditBean providerEvent(){
         EditBean eventData = new EditBean();
         eventData.setEdit1("hello world");
         Return eventData;
     }

     @Override
     Protected void onDestroy() {
         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 bus.post ("... 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.




Example:


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 Subject.java
Public class Subject {
     Private List<Observer> observers
             = new ArrayList<Observer>();
     Private Observer observer;
     Private int state;
     / / Change situation
     Public int getState() {
         Return state;
     }
     Public void setState(int state) {
         This.state = state;
     }
     //binding
     Public void binding(Observer observer) {
         Observers.add(observer);
     }
     /**
      * unbinding (logout observer, sometimes not used in the instance)
      **/
     Public void unbinding(Observer cls) {
         If (cls == null) throw new NullPointerException();
         Observers.remove(cls);
      
     }
     //Notice
     Public void notifyAllObservers() {
         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 FirstObserver extends Observer {
     Public FirstObserver(Subject subject) {
         This.subject = subject;
         Subject.binding(this);//binding
     }
     @Override
     Public void update() {
         / / used to update the 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 observer
         Subject subject = new Subject();
         / / Load the observer
         FirstObserver firstObserver = new FirstObserver(subject);
         SecondObserver secondObserver = new SecondObserver(subject);
         ThirdObserver thirdObserver = new ThirdObserver(subject);
         subject.setState(2);
         subject.notifyAllObservers(); 


Unbind
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: 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.