AndroidEventBus V1.0.4 released

Source: Internet
Author: User
Tags eventbus

AndroidEventBus V1.0.4 released

If you do not know about AndroidEventBus, go to AndroidEventBus design and implementation. The github address of the AndroidEventBus library is here.

The new feature supports Sticky events. The weak reference holds subscribers and does not require manual unregister to avoid Memory leakage. What is a Sticky event?

Some people may not be familiar with the Sticky event. Sticky means Sticky. In Android development, Sticky events only indicate the special types of events that the event consumer can register after the event is published. In Android, there is such an instance, namely Sticky Broadcast, that is, Sticky Broadcast. Under normal circumstances, if the sender sends a broadcast, and the Receiver registers its own Receiver only after the broadcast is sent, then the Receiver cannot receive the broadcast just now. For this reason, Android introduces StickyBroadcast, after the broadcast is sent, the broadcast (Intent) is saved, so that the Receiver can receive the broadcast that has just been published after registering the Receiver er. This allows us to handle some events in advance and deliver these events to consumers when there are consumers.

AndroidEventBus also provides this function. The difference is that AndroidEventBus stores all Sticky events. If an event does not need to be stored, it needs to be removed manually. The user publishes an event in the form of Sticky, and the consumer needs to register the event in the form of Sticky. Of course, this kind of registration function is the same as the general registration function except to receive the Sticky event, other types of events are also processed normally. To publish and receive Sticky events, follow these steps:

1. Publish the Sticky event;

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

2. subscriber registers as Sticky at a certain time

Public class MyReceiver {public MyReceiver () {EventBus. getDefault (). registerSticky (this);} @ Subscriber private void onStickyEvent (String info) {System. out. println ("events received:" + info );}}

When a mycycler object is constructed at a certain time point, the mycycler object will be registered to EventBus in the form of Sticky. In this case, the previously published "hello" event will be received by the mycycler object, thereforeonStickyEventFunction to implement the specific logic in the function.Of course, do not forget to deregister the mysubscriber at a certain time. the subscriber's function in the form of weak reference has not been completed yet!The whole process is over ~

Use Cases of Sticky events

In the above section, we briefly describe the basic steps for using Sticky events. Here we will take a specific example to look at the use cases of Sticky events in development.

During the development process, we often need to pass values between activities. Our practice is to insert data into Intent and set a key for each data. When the data we pass is an entity class, our class also needs to implement the serialization interface, such as Parcelable or Serializable. For example, we need to pass a user object to the user's personal information display page. Our general practice is as follows:

User. java class:

// Implement serialization of the object class public class User implements Parcelable {String name; String phoneNum; // other fields omit public User (String aName) {name = aName ;} public User (Parcel in) {super (in); name = in. readString (); phoneNum = in. readString ();} // Code omitted @ Override public void writeToParcel (Parcel dest, int flags) {dest. writeString (name); dest. writeString (phoneNum);} public static final Parcelable. creator
  
   
CREATOR = new Parcelable. Creator
   
    
() {@ Override public User createFromParcel (Parcel source) {return new User (source) ;}@ Override public User [] newArray (int size) {return new User [size] ;}};}
   
  

Then we will pass the user data in an Activity to the personal information interface ProfileActivity. 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 the processing function of a click event, we pass data to ProfileActivity through Intent. Let's look at the code that ProfileActivity extracts data from Intent.

Public class ProfileActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_profile); // obtain the data Bundle extraBundle = getIntent () from the Bundle (). getExtras (); if (extraBundle! = Null) {User user = extraBundle. getParcelable ("user ");}}}

OK. Now the entire process is complete.

Big brother, I just need to upload data! Why!
This method generates a lot of sample code and makes the logic more complex and error-prone. Let's take a look at how to implement the Sticky event.

User. java class:

// Implement serialization of the object class public class User {String name; String phoneNum; // other fields are omitted public User (String aName) {name = aName;} // Code omitted}

First, the User class does not need to implement the serialization interface, avoiding the sample code. Then, directly publish the User object in MainActivity as a Sticky event.

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 // publish the Sticky event EventBus. getDefault (). postSticky (aUser); // jump to the ProfileActivity page Intent intent = new Intent (this, ProfileActivity. class); startActivity (intent );}}

Finally, let's see how ProfileActivity receives data.

Public class ProfileActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_profile); // register EventBus as Sticky. getDefault (). registerSticky (this) ;}@ Subscriber private void receiveUser (User info) {// implement your logic here, and info is the passed User object }}

In ProfileActivity, we register ProfileActivity as a subscriber to the bus. In this case, ProfileActivity receives the Sticky event published above, which is the User object. In this case, the receiveUser function in ProfileActivity is triggered. The info parameter is the user information object of the Sticky event. You can implement your own logic in receiveUser.

Yes!We have not logged out the subscriber in onDestory, that is, we have not called the EventBus unregister () function. This is one of the latest features and is currently the only event bus library that does not need to be manually logged out.

Is the problem much simpler ~ What other scenarios can Sticky events be used? Should Sticky events be automatically removed after consumption? You can think about these questions or leave me a message (simplecoder.h@gmail.com), thank you.

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.