Androideventbus version V1.0.4 released.

Source: Internet
Author: User
Tags eventbus

If the Androideventbus do not understand the students please go to androideventbus design and implementation. The GitHub address of the Androideventbus library is here.

New features
    1. Support sticky events;
    2. Weak references hold subscribers without manual unregister to avoid memory leaks.
What is the sticky event?

About the sticky event some classmates may not be very familiar with, sticky meaning is sticky. In Android development, the sticky event is a special type of event that the event consumer registers only after the event has been published. There is an example of this in Android, the sticky broadcast, the sticky broadcast. Normally, if the sender sends a broadcast and the receiver registers his receiver after the broadcast is sent, the receiver cannot receive the broadcast, and the Stickybroadcast is introduced for Android. The broadcast (Intent) that was just sent is saved after the broadcast is sent, so that when the receiver registers receiver, it can receive a broadcast that has just been released. This allows us to deal with events in advance so that customers can be delivered to consumers.

Androideventbus also provides a feature that differs from Androideventbus stores all sticky events and requires manual removal if an event does not need to be stored. The user publishes the event through the sticky, and the consumer also needs to register through the sticky form, of course, this kind of registration in addition to receive sticky event and the normal registration function is the same, other types of events will be normal processing. The steps to publish and receive the sticky event are as follows:

1, release sticky events;

EventBus.getDefault().postSticky("hello");

2. Subscribers are registered in sticky form at some point

publicclass MyReceiver {    publicMyReceiver() {        EventBus.getDefault().registerSticky(this);    }    @Subscriber    privatevoidonStickyEvent(String info) {        System.out.println("接收到事件 : " + info);    }}

When the Myreceiver is constructed at some point, the Myreceiver object is registered to Eventbus in sticky form, and the previously published "Hello" event is received by the Myreceiver object, so the function is executed onStickyEvent . Implement the specific logic in the function. of course, don't forget to log out of myreceiver at some point and hold the subscriber's function in the form of a weak reference is not complete! This is the end of the process ~

The use of sticky events

The basic use steps of the sticky event are briefly described above, and here we take a concrete example to see the use of the sticky event in development.

In the development process, we often need to pass values between the activity, our practice is to plug the data into the intent, and set a key for each data. When the data we pass is an entity class, our class also needs to implement a serialization interface, such as parcelable or serializable. For example, we need to pass a user object to the user's personal information presentation page. Our usual practice is this:

User.java class:

//Entity classes for serialization Public  class User implements parcelable {String name; String Phonenum;//other fields omitted         Public User(String aName)        {name = AName; } Public User(Parcel in) {Super(in);            Name = In.readstring ();        Phonenum = In.readstring (); }//Code omission        @Override         Public void Writetoparcel(Parcel dest,intFlags) {dest.writestring (name);        Dest.writestring (Phonenum); } Public Static FinalParcelable.creator<user> Creator =NewParcelable.creator<user> () {@Override         PublicUserCreatefromparcel(Parcel Source) {return NewUser (source); }@Override         PublicUser[]NewArray(intSize) {return NewUser[size]; }    }; }

Then we will pass this user data to the personal information interface profileactivity in an activity. The code is as follows:

public  class  mainactivity  extends  activity  { //a click event   @Override  public  void  onclick  (View v) {User Auser = new  User ( "mr.simple" ); Auser.phonenum =  "123456" ; //Other data  Intent Intent = new  Intent (this , Profileactivity.class); Intent.putparcelable ( "user" , auser); StartActivity (Intent); }}

In a Click event handler we pass the data to profileactivity through intent. Let's look at the code that profileactivity the data out of the intent.

public  class  profileactivity  extends  activity  { @ Override  protected  void  oncreate  (Bundle savedinstancestate) {super . OnCreate (        Savedinstancestate);        Setcontentview (R.layout.activity_profile);        //get data from bundle         Bundle Extrabundle = Getintent (). Getextras (); if  (Extrabundle! = null )        {User user = Extrabundle.getparcelable ( "User" ); }    }}

OK, this is the end of the process.

Big Brother, I just need to pass a data Ah! Why bother!
This approach produces a lot of boilerplate code and makes logic more complex and error-prone. Let's look at how the sticky event is implemented.

User.java class:

// 实体类实现序列化publicclass User  {        String name ;        String phoneNum;        // 其他字段省略        publicUser(String aName) {            name = aName ;        }        // 代码省略 }

First, the user class does not need to implement a serialization interface and avoids those boilerplate code. You can then publish the user object directly as a sticky event in mainactivity.

 Public  class mainactivity extends Activity {    //One click event    @Override      Public void OnClick(View v) {User Auser =NewUser ("Mr.simple"); Auser.phonenum ="123456";//Other data        //Post sticky eventsEventbus.getdefault (). Poststicky (Auser);//Jump to Profileactivity pageIntent Intent =NewIntent ( This, Profileactivity.class);    StartActivity (Intent); }}

Finally, let's see how profileactivity receives the data.

 Public  class profileactivity extends Activity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_profile);//Register in sticky formEventbus.getdefault (). Registersticky ( This); }@Subscriber    Private void Receiveuser(User info) {//Implement your logic here, info is the user object passed over}}

In profileactivity we register profileactivity itself as a subscriber to the bus, and Profileactivity receives the sticky event posted above, which is the user object. In this case, the Receiveuser function in profileactivity is triggered, and the info parameter is the user information object of the sticky event, which realizes its logic in Receiveuser.

Yes! we did not unregister subscribers in Ondestory, that is, we did not call Eventbus's unregister () function, which is one of the newest features and the only event bus library that does not require manual logoff at this time.

The question is not much simpler--what other scenarios can you use the sticky event? Should the sticky event be automatically removed after consumption? These questions can be self-thinking or give me a message ([email protected]), thank you.

Androideventbus version V1.0.4 released.

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.