Introduction to the

  1. Android event publish/subscribe framework
  2. Event passing can be used to communicate between the four components of Android
  3. The benefits of EventBus are simplicity of code, simplicity of use, and sufficient decoupling of event publishing and subscription.

use

  • 1. Define the event
  • 2. Prepare subscribers
  • 3. Subscribers need to register and unregister themselves on the bus
  • 4. Send an event. Any recipient matching the event can receive the event

Source code analysis

Registered EventBus. GetDefault (). The register (this);

GetDefault () method

  • GetDefault is a singleton method that returns an instance of an EventBus object
  • Object building: Built through EventBusBuilder, three core Posters for thread scheduling
    • HandlerPoster
    • BackGroundPoster
    • AsyncPoster

The subscribe annotation/threadMode

  • The following code, valid at run time, describes the method
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface Subscribe {
        ThreadMode threadMode() default ThreadMode.POSTING;
    
        boolean sticky() default false;
    
        int priority() default 0;
    }
    Copy the code
  • ThreadMode: Five enumerated values
    • POSITING: indicates the default thread
    • MAIN: MAIN thread execution
    • MAIN_ORDERED: Unlike MAIN, events are always queued to be sent. This ensures that the POST call is non-blocking.
    • BACKGROUND: BACKGROUND thread execution
    • ASYNC: The subscriber is invoked in a separate thread. This is always independent of the publishing thread and the main thread
  • Sticky events: Event consumers who register after an event is published can also receive a special type of event
    • For example, a sticky broadcast saves the broadcast that was just sent after the broadcast is sent
    • AndroidEventBus stores all Sticky events

The register subscriptions

It’s essentially a collection of ways to find subscriptions

The subscribe method completes the subscription

  1. First determine whether the event has been registered
  2. It is then added to the List of subscriptionsByEventType values by priority
  3. It is then added to the List of typesBySubscriber’s values
  4. Distribute events: checkPostStickyEventToSubscription

Post Send event

  • checkPostStickyEventToSubscription -> postToSubscription(newSubscription, stickyEvent, isMainThread());
  • Do different send operations depending on the thread