一步一步帶你瞭解EventBus3.1.1 原始碼

sun_xin發表於2018-07-20

EventBus原始碼分析

EventBus 是一個事件匯流排框架,解決了元件之間通訊的問題。使用了觀察者模式。使程式碼更加簡潔

簡單使用

1.引入依賴 compile 'org.greenrobot:eventbus:3.1.1'

2.定義事件

public class MessageEvent {
    private Object msg;

    public MessageEvent(Object msg) {
        this.msg = msg;
    }

    public Object getMsg() {
        return msg;
    }

    public void setMsg(Object msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "MessageEvent{" +
                "msg=" + msg +
                '}';
    }
}
複製程式碼

3.註冊與反註冊

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EventBus.getDefault().register(this);
    mTextView = findViewById(R.id.tv);
}


@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}
複製程式碼

4.在某個地方傳送事件

EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));
複製程式碼

5.在註冊頁面接收事件

@Subscribe(threadMode = ThreadMode.MAIN, priority = 100, sticky = false)
public void onMessageEventPost(MessageEvent messageEvent) {
    Log.e(TAG, "onMessageEventPost: " + messageEvent.getMsg().toString());
    mTextView.setText(messageEvent.getMsg().toString());
}

@Subscribe(threadMode = ThreadMode.MAIN, priority = 150, sticky = false)
public void onMessageEvent(MessageEvent messageEvent) {
    Log.e(TAG, "onMessageEvent: " + messageEvent.getMsg().toString());
    mTextView.setText(messageEvent.getMsg().toString());
}
複製程式碼

註冊分析

EventBus.getDefault().register(this);這行程式碼都做了什麼呢,大眼一看感覺好像是用的單例模式構造物件。

建立EventBus物件

/** Convenience singleton for apps using a process-wide EventBus instance. */
/*使用雙重鎖校驗建立EventBus物件*/
public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}
複製程式碼

註冊

/**
 * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
 * are no longer interested in receiving events.
 * 引數型別是Object,可以接收各種型別。
 * <p/>
 * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
 * The {@link Subscribe} annotation also allows configuration like {@link
 * ThreadMode} and priority.
 */
public void register(Object subscriber) {
    // 使用反射獲取到類的位元組碼檔案
    Class<?> subscriberClass = subscriber.getClass();
    // 通過反射獲取該類中所有 包含 @Subscribe 註解的方法,得到的是一個集合
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    // 上鎖
    synchronized (this) {
     // 迴圈遍歷所有的方法,進行訂閱
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
        // 訂閱 subscriber 在這裡表示就是MainActivity
        // subscriberMethod 在這裡表示方法有兩個  onMessageEventPost   onMessageEvent
            subscribe(subscriber, subscriberMethod);
        }
    }
}
複製程式碼

來到了SubscriberMethodFinder類中,從類名直接來看,是訂閱者方法搜尋者,通過類的位元組碼檔案找到所有訂閱者的方法,這個類是在Eventbus的構造方法中建立的。


private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    // 這裡使用Map做了一個快取,先從Map中找,如果沒有在通過反射去遍歷尋找。能提高效率
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
   // 如果Map中存在,就直接取出來
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //ignoreGenerateIndex這個值表示是否忽略註解器生成的MyEventBusIndex
    // 這個值預設是false,表示可以通過EventBusHandler來設定他的值
    if (ignoreGeneratedIndex) {
    // 利用反射來獲取訂閱類中所有的訂閱方法資訊
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
     // 第一次走到這裡 從註解器生成的MyEventBusIndex類中獲得訂閱類的訂閱方法資訊
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    if (subscriberMethods.isEmpty()) {
        throw new EventBusException("Subscriber " + subscriberClass
                + " and its super classes have no public methods with the @Subscribe annotation");
    } else {
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}
複製程式碼
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    // 這裡有用到享元模式
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        findState.subscriberInfo = getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}
複製程式碼

通過反射獲取訂閱類中的訂閱方法資訊

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // This is faster than getMethods, especially when subscribers are fat classes like Activities
     // 反射獲取類中所有的方法
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    // 迴圈遍歷
    for (Method method : methods) {
      // 拿到方法的修飾符
        int modifiers = method.getModifiers();
     // 方法只能是 public ,如果設定成private 和 static abstract 的話將會報錯
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
       // 拿到引數型別資訊
            Class<?>[] parameterTypes = method.getParameterTypes();
       // 只允許包含一個引數
            if (parameterTypes.length == 1) {
         // 拿到方法上的註解資訊
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
            // 如果註解不為空,就獲取註解當中的引數事件型別
                    Class<?> eventType = parameterTypes[0];
            // 檢測新增
                    if (findState.checkAdd(method, eventType)) {
               // 獲取 threadMode 
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
              // 向集合裡面新增,解析方法註解的所有屬性
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException("@Subscribe method " + methodName +
                        "must have exactly 1 parameter but has " + parameterTypes.length);
            }
        } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}
複製程式碼

當我們獲取到所有的標有 @subscribe 註解的方法之後,就要開始進行訂閱subscribe 操作,主要做的工作就是解析所有 subscriberMethod 的eventType,然後解析成Map<Class<?>, CopyOnWriteArrayList> subscriptionsByEventType;的格式,key 為引數型別的class,value是儲存了Subscription的一個列表,Subscription包含兩個屬性,一個是subscriber(訂閱者類),一個是subscriberMethod,就是註解方法


private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    // 獲取方法引數的class  ,在我們的這裡demo中表示 MessageEvent.class
    Class<?> eventType = subscriberMethod.eventType;
    // 構建一個 Subscription
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    // subscriptionsByEventType 是一個Map,key是方法引數的Class:MessageEvent.class.value 是這裡相當於做了一個快取操作
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    // 第一次取出的為空
    if (subscriptions == null) {
    // 新建一個陣列,該陣列執行緒安全
        subscriptions = new CopyOnWriteArrayList<>();
    // 新增元素進去
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
    //如果不為空,判斷是否包含。如果包含就丟擲異常
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                    + eventType);
        }
    }
    // 處理優先順序
    int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }
    // 通過 subscriber 獲取  List<Class<?>>  typesBySubscriber 也是一個Map,key儲存的是訂閱者,value是所有訂閱者裡面方法引數的Class
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    // 將此事件類加入到訂閱者的事件類列表中
    subscribedEvents.add(eventType);
    //處理粘性事件
    if (subscriberMethod.sticky) {
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
    if (stickyEvent != null) {
        // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
        // --> Strange corner case, which we don't take care of here.
        postToSubscription(newSubscription, stickyEvent, isMainThread());
    }
}
複製程式碼

Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType 這個Map的資料結構,subscriber -> MainActivity, subscriberMehtod -> onMessageEventPost

**粘性事件(sticky event):**普通事件是先註冊,然後傳送事件才能收到;而粘性事件,在傳送事件之後再訂閱該事件也能收到。此外,粘性事件會儲存在記憶體中,每次進入都會去記憶體中查詢獲取最新的粘性事件,除非你手動解除註冊。

post()傳送分析

EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));

// ThreadLocal 是一個建立執行緒區域性變數的類,,通常情況下我們建立的變數是可以被任何一個執行緒訪問的,但是ThreadLocal建立的變數只能被當前執行緒訪問,其他
// 執行緒無法訪問和修改。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};

/** Posts the given event to the event bus. */
public void post(Object event) {
  // event 就是我們傳送的時間 MessageEvent
  // 獲取到當前執行緒的變數資料
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
  // 把事件新增到事件佇列中
    eventQueue.add(event);
   // 判斷是否處在事件釋出狀態,如果沒有,就傳送事件,並且一直保持釋出狀態。
    if (!postingState.isPosting) {
     // 是否在主執行緒
        postingState.isMainThread = isMainThread();
    // 保持釋出狀態
        postingState.isPosting = true;
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            while (!eventQueue.isEmpty()) {
         // 不斷的傳送事件
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}
複製程式碼

傳送事件

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
   // 事件的Class,就是 MessageEvent.class
    Class<?> eventClass = event.getClass();
   // 是否找到訂閱者
    boolean subscriptionFound = false;
   // 是否支援事件繼承,預設為true
    if (eventInheritance) {
     // 獲取到所有的事件的父類和介面
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
         // 依次向 eventClass 的父類或介面的訂閱方法傳送事件
         // 只要有一個事件傳送成功,返回 true ,那麼 subscriptionFound 就為 true
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
     // 傳送事件
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
   // 如果沒有訂閱者
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
     // 得到 subscription 列表,這個物件裡包含兩個部分,見上圖
        subscriptions = subscriptionsByEventType.get(eventClass);
    }

    if (subscriptions != null && !subscriptions.isEmpty()) {
    // 遍歷
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted = false;
            try {
         // 傳送事件
                postToSubscription(subscription, event, postingState.isMainThread);
         // 是否被取消了
                aborted = postingState.canceled;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
       // 如果被取消了就跳出迴圈
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}

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);
    }
}
複製程式碼

BACKGROUND 與 ASYNC 的區別: 前者中的任務是序列呼叫,後者是非同步呼叫。

總結: 事件的傳送和接收,主要是通過subscriptionsByEventType這個列表,Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType。我們將訂閱即接收事件的方法儲存在這個列表,釋出事件的時候在遍歷列表,查詢出相對應的方法並通過反射執行。

相關文章