A few questions to explore

  • The process principle of
  • Send messages, how to do thread switch
  • What is a sticky event and how it works
  • Disadvantages of Using EventBus

process

1. Use register to register a method

ConcurrentHashMap is used to store methods, with key as the registered class and value as the method in the registered class

  • Annotation 1 is for finding methods annotated by the @SUBSCRIBE annotation
  • Annotation 2 caches the lookup method

2. Post Sends events

In the EventBus class

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
                if(mainThreadPoster ! =null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: "+ subscription.subscriberMethod.threadMode); }}Copy the code

Implementing thread switching

This step is the actual method call, via reflection

3. What are sticky events

Normal events must be registered before they can be successfully sent, whereas sticky events are cached through ConcurrentHashMap and then sent

    public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }
Copy the code

StickyEvents is ConcurrentHashMap

Deficiency in

Although EventBus is simple to decouple, heavy use can clutter your program