Detailed explanation of EventBus 3. Quick use of x

  • 2021-08-21 21:37:06
  • OfStack

EventBus can easily communicate between components, which is more decoupled and better than broadcasting.

Introduction to EventBus 3

EventBus is a decoupling tool to optimize event transfer between Android components. Event transfer between different components is realized through publish/subscribe event bus.

Prior to EventBus 3, the greenrobot team resisted using the annotation framework for performance reasons. The current EventBus3 begins to use annotations to declare how subscription events are handled. Although Android 6 and ART are available at present, the performance impact caused by Java reflection is still not well solved.

In EventBus3, the greenrobot team improved performance by retrieving all annotation codes at compile time and then generating a class containing all the data that can be obtained at runtime, which made EventBus3 faster than other eventbus. A performance comparison with otto will be posted later.

Differences between EventBus 3 and EventBus 2. x

Callback method changes

Because of the changes to API, EventBus3 is incompatible with the previous version of EventBus, because the previous version (EventBus 2.x) requires writing the corresponding onEvent () method after registering the event, including onEvent (), onEventAsync (), onEventBackground () and onEventMainThread () corresponding to @ Subscrible, @ Subscrible (threadMode = ThreadMode. ASYNC), @ Subscribe (threadMode = ThreadMode. BACKGROUND) and @ Subscribe (threadMode = ThreadMode. In EventBus 3, when threadMob is not declared, the default thread mode is ThreadMode. POSTING.

Exception fault-tolerant handling

In EventBus3, if the program goes wrong in the @ Subscrible annotated method, the program crash is not immediately made, but the exception is intercepted by EventBus and the error log is printed.

The user can configure the object after obtaining the instance of EventBus through EventBusBuilder to decide whether to throw exception information when processing event:


 eventBus = EventBus.builder().sendNoSubscriberEvent(false)    
       .sendSubscriberExceptionEvent(false)            
       .throwSubscriberException(BuildConfig.DEBUG) // Only when debug Mode, an error exception is thrown  
       .build();

The above code uses the Builder design pattern to build and return 1 eventBus instance. In the debugging phase, you can find errors directly by Crash when the program is abnormal.

Quick use

1. Compile


compile 'org.greenrobot:eventbus:3.1.1'

2. Customize event classes


public class MessageEvent {
  //  Member variables are created according to their own needs 
  private int type;

  //  Passing data through constructors 
  public MessageEvent(int type) {
    this.type = type;
  }

  public int getType() {
    return type;
  }

  public void setType(int type) {
    this.type = type;
  }
}

3. Registration events and deregistration

1 In general, register in the OnCreate () method:


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

Correspondingly, deregister in OnDestroy ():


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

4. Send an event


EventBus.getDefault().post(new MessageEvent(type));

5. Receive and handle events


/**
* @Subscribe  Annotations must be written, and threads need to specify 
*  Method name is optional 
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
  switch (event.getType()){
    // do your thing
  }
}

The threading model mentioned above has five kinds:

POSTING (default): The thread that handles the event is the same thread as the thread that publishes the event; MAIN: In Android, event handling methods are called in the main thread (UI thread) and cannot perform time-consuming operations; MAIN_ORDERED: In Android, the event handling method is called in the main thread (UI thread). Unlike MAIN, this event will always be queued for publication, which ensures that event publication will not be blocked; BACKGROUND: In Android, event handling methods are called in a background thread, so UI operations cannot be performed. If the thread publishing the event is the main thread (UI thread), the event handler will open a background thread, and if the thread publishing the event is in the background thread, the event handler will use this thread; ASYNC: No matter which thread the event publishes, the event handling method will always create a new subthread to run and cannot perform UI operations.

Related articles: