An overview,

EventBus is a publish/subscribe EventBus optimized for Android. When we carry out project development, we often need to communicate between application components and background threads, such as requesting data in the sub-thread, notifies UI through Handler or broadcast after data request is completed, and two Fragment self-checks can communicate through Listener, etc. When our project becomes more and more complex, it uses intents, handlers and BroadcastReceivers to communicate between modules and between modules and background threads, the code volume is large and highly coupled. Instead of Intent, Handler, and BroadcastReceiver, EventBus can transmit messages between fragments, activities, services, and threads. It simplifies the communication between components within the application and between components and background threads. The overhead is low, the code is more elegant, and the sender and receiver are decoupled.

Two, knowledge points

(1) Three elements

  1. The Event Event. It can be any type of object.
  2. Subscriber Event Subscriber. Before EventBus3.0 we had to define the methods that started with onEvent, onEvent, onEventMainThread, onEventBackgroundThread, and onEventAsync. After 3.0, the name of the method can be arbitrary, but the annotation @subscribe() is required, and the thread model is specified. The default is POSTING.
  3. Publisher Publisher of the event. We can publish events in any thread, usually using the default singleton eventBus.getDefault () to get an EventBus Object and then call the POST (Object) method.

(2) Four kinds of thread models-threadMode

EventBus3.0 has four threading models:

  1. POSTING (the default) means that the event handler thread is in the same thread as the POSTING thread.
  2. MAIN indicates that the thread of the event handler is in the MAIN thread (UI), so time-consuming operations cannot be performed there.
  3. BACKGROUND indicates that the event handler thread is in the BACKGROUND thread and therefore cannot perform UI operations. If the thread publishing the event is the main thread (UI thread), the event handler will start a background thread, and if the thread publishing the event is a background thread, the event handler will use this thread.
  4. ASYNC means that no matter which thread the event is published on, the event handler will always create a new child thread to run and also cannot perform UI operations.

Three, basic use

(I) Introduce EventBus

compile 'org. Greenrobot: eventbus: 3.0.0'
Copy the code

(2) Define the event class

Event classes are passed events, and information sent from one component to another can be stored in a class that is an event that EventBus sends to subscribers.

public class MessageEvent {
    private String message;
    public MessageEvent(String message){
        this.message = message;
    }

    public String getMessage() {returnmessage; }}Copy the code

(iii) Registration events

@Override
protected void onCreate(Bundle savedInstanceState) {           
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     EventBus.getDefault().register(this);
} 
Copy the code

(4) Cancellation of registration

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}
Copy the code

(v) Receiving events

// The subscription method, when the event is received, Subscribe(threadMode = threadmode. MAIN) public void onEvent(MessageEvent){Subscribe(threadMode = threadmode. MAIN) public void onEvent(MessageEvent){ Toast.makeText(MainActivity.this, messageEvent.getMessage(), 0).show(); }Copy the code

(6) Sending events

EventBus.getDefault().post(messageEvent);
Copy the code

Fourth, sticky events

Sticky events are events that can be received even after being sent and then subscribed to. Normal events are registered and then bound.

For example, there is a requirement in a project to send events in FirstActivity to SecondActivity for event processing. If the event is sent via eventBus.getDefault.post (xx) in FirstActivity, the message will not be received in SecondActivity. Because EventBus, which SecondActivit uses to receive messages, has not been registered yet, subscribers have not been generated, although the publisher has sent messages. So sending sticky events should read something like this:

(I) Sending sticky events

EventBus.getDefault().postSticky(messageEvent);
Copy the code

(2) Receiving viscous events

@Subscribe(threadMode = ThreadMode.MAIN , sticky = true)
public void onEvent(MessageEvent messageEvent) {
    Toast.makeText(MainActivity.this, messageEvent.getMessage(), 0);
}
Copy the code

Fifth, pay attention to

  1. The receiving event method must be of type public void and have only one parameter representing EventType.
  2. The receiving of the message determines which receive event method to execute based on the type of the parameter, specifically the class name in the parameter. That is, the subscriber’s processing method determines the subscription function based on the type of subscription event.
  3. Each event can have multiple subscribers.
  4. The same onEvent function cannot be registered twice, so it cannot be registered in the same class and its parent.