EventBus from zero to one (one)

1. What is EventBus

1.EventBus is an Android event publish/subscribe framework

Simplifies Android event delivery by decoupling publishers and subscribers. Event delivery can be used not only for communication between the four major components of Android, but also for communication between user asynchronous threads and the main thread, etc. Traditional event delivery methods include: Handler, BroadCastReceiver, and interface callback. Compared with EventBus, EventBus has more concise code, simpler code, and fully decoupled event publishing and subscription. Let's first understand some of its basic concepts:

(1) Event: It can be called a message, but it is actually an object

(2) Event Type (EventType): refers to the Class to which the event belongs

(3) Subscriber: Subscribe to an object of a certain event type. When a publisher publishes such an event, EventBus will execute the subscriber's function modified by the Subscribe annotation. This function is called an event response function. Subscribers subscribe to an event type through the register interface, and unsubscribe through the unregister interface. Subscribers have priorities, and subscribers with higher priorities can cancel events and continue to distribute events to subscribers with lower priorities. By default all subscribers have a priority of 0

(4) Publisher: An object that publishes an event, and publishes the event through the EventBus.getDefault.post method.

Second, the use of EventBus

The advantage of EventBus is that the code is concise and simple. So its use is relatively simple.

Add its dependencies before using it:

compile 'org.greenrobot:eventbus:3.1.1'

The general process is divided into three steps:

(1) Define the event (Event)

(2) Prepare subscribers

(3) Send event

Let me give an example to be more familiar with this process:

(1) 1. First come a message class (javaBean)

/**
* javabean: message class
*/

public class Messages {
    private String message;

    public Messages(String message) {
        this.message = message;
    }

    public String getMessage() {

        return message;
    }
}

(2) Prepare two activities

The first activity is used to jump to the second activity and receive messages sent by the second activity.


/**
* 1. Jump to the second activity
* 2. Get the message sent by the second activity
*/

public class MainActivity extends AppCompatActivity {

    private Button btnSkipActivity;
    private TextView tvWaitMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSkipActivity=(Button)findViewById(R.id.skip_next);
        tvWaitMsg=(TextView)findViewById(R.id.tv_waitMsg);
        btnSkipActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
        //Register EventBus and become a subscriber
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy ();
        //Unregister when destroying the activity
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
   public void onEventMainThread(Messages msg){
       String obj="Receive notification:"+msg.getMessage();
       tvWaitMsg.setText(obj);
       Toast.makeText(this,obj,Toast.LENGTH_SHORT).show();

   }
}
The second activity is for sending messages
/**
* Send messages to subscribers
*/
public class SecondActivity extends AppCompatActivity {

    private Button btnSendMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_second);
        btnSendMsg=(Button)findViewById(R.id.send_mes);
        btnSendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new Messages("The boss is gone, you can play the game..."));
            }
        });
    }
}
Running result: Click the button in the figure, it will jump to the second activity page, and send a message to all subscribers (the first activity here), you can see that the TextView here has received the message and updated the UI


3. Advanced use of EventBus

The first activity above has such a method, this is where subscribers receive messages:

@Subscribe(threadMode = ThreadMode.MAIN)
   public void onEventMainThread(Messages msg){
       String obj="Receive notification:"+msg.getMessage();
       tvWaitMsg.setText(obj);
       Toast.makeText(this,obj,Toast.LENGTH_SHORT).show();

Informing the observer that an event occurs is implemented through the EventBus.post function. This process is called event publishing. The observer is informed that the event occurs is called event reception, which is implemented through the following subscription function.

(1) onEvent
(2) onEventMainThread
(3) onEventBackgroundThread
(4) onEventAsync
These four subscription functions all start with onEvent. What is the difference between them?
  (1) onEvent: If onEvent is used as the subscription function, then on which thread the event is published, onEvent will run in this thread, that is to say, the thread that publishes the event and the thread that receives the event are in the same thread. When using this method, time-consuming operations cannot be performed in the onEvent method, and event distribution delays may occur if time-consuming operations are performed.
(2) onEventMainThread: If onEventMainThread is used as the subscription function, no matter which thread the event is published in, onEventMainThread will be executed in the UI thread, and the received event will run in the UI thread, which is very useful in Android , because in Android, you can only follow the new UI in the UI thread, so time-consuming operations cannot be performed in the onEvnetMainThread method.
(3) onEventBackground: If onEventBackgrond is used as the subscription function, then if the event is published in the UI thread, then onEventBackground will run in the sub-thread. If the event is originally published in the sub-thread, then the onEventBackground function is directly in the sub-thread. execute in the child thread.

(4) onEventAsync: Use this function as a subscription function, then no matter which thread the event is published on, a new child thread will be created and then execute onEventAsync.

So far there is a problem like this:

When a message is sent, how does EventBus know which function to call?

This depends on what the passed object instance is, and determines which subscription function to call by matching the parameter type of the subscriber's subscription function.

Then if there are two subscription functions with the same parameter instance, both subscription functions will be called! ! !

Here we have a preliminary understanding and use of EventBus. So why is it so simple to achieve a more complex function? In this regard, if you want to know why it is so magical, you need to look at the source code to reveal its true colors.

The analysis of the source code will be introduced in a later blog haha




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325561768&siteId=291194637
one
ONE