Android面試框架源碼-EventBus源碼初探

  1. EventBus.getDefault().register(this)
public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

這個方法會得到 Activity或者Fragment的class, 然後以class 爲key 把所有用@Subscribe標記的方法找到保存在一個Map集合中。

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    //....省略

    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    if (subscriberMethods.isEmpty()) {
        //....省略
    } else {
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

一個class 對應一個List<SubscriberMethod> 然後遍歷List把每個SubscriberMethod 封裝成對應的new Subscription(subscriber, subscriberMethod)同時得到eventType (就是@Subscribe註解方法的參數類型) class ,從另一個map中取出一個ArrayList<Subscription> 然後把新的Subscription放在這個list集合中,同時還回去判斷他是否是sticky 。

// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    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;
        }
    }

    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);
        }
    }
}

至此所有的訂閱者都保存在subscriptionsByEventType map集合中,key是被訂閱方法參數類型的class,value是一個訂閱方法集合Subscription,Subscription內包含有Activity 或者Fragment的class 以及 對應的SubscriberMethod.

  1. EventBus.getDefault().post(message)
    它會首先從ThreadLocal 中拿到當前線程 判斷是主線城還是子線程,然後獲取到當前線程的線程隊列,把消息內容添加進去。最後循環執行postSingleEvent
public void post(Object event) {
   //從ThreadLocal 中拿到當前線程信息
    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 {
            //循環去post隊列中的消息
            while (!eventQueue.isEmpty()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

在發送消息的時候他還會 獲取消息類型的父類以及接口類的class,最後挨個尋找這些Class對應的Subscription ,從subscriptionsByEventType map集合取出來,調用postToSubscription 方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        //獲取當前消息類型的父類 class以及接口class
        //比如post是ArrayList  那麼他還會獲取到List類型的SubscriberMethod
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    // 省略。。。
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //從上一步中的map中取出對應的EventType subscriptions
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        //遍歷執行發送消息的方法
        //Subscription 身上自帶 SubscriberMethod和Subscriber訂閱者
        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;
}

最後根據subscriberMethod.threadMode以及當前所在線程然後判斷如何發送消息

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);
    }
}

總結

EventBus 通過註冊方法,將觀察者保存起來,這個過程做了兩件是,第一件是觀察者身上的所有@subscribe 註解註釋的方法封裝成一個SubscribeMethod保存在一個集合中,一個Activity或者Fragment對應一個List<SubscribeMethod> 然後遍歷這個集合拿到所有的SubscribeMethod的方法的參數類型的class。根據這個class 去另外一個集合中獲取一個list集合subscriptionsByEventType,這個集合是 一個回調方法參數類型對應一個List<Subscription>。 其中Subscription 傳入了兩個參數一個是Activity或者fragment實例一個是對應的SubscribeMethod。 如果找不到就創建一個list 保存。
EventBus.post(Object object)方法根據上文的判斷,post的參數類型至關重要的, 他首先拿到object這個類相關的所有類型,包括父類還有實現的接口,保存在一個list集合中。然後遍歷這個集合,根據class 從上面的subscriptionsByEventType集合中去取對應的List<Subscription> ,這個Subscription 上文也說過,他包含了 Activity /fragment的實例,還有SubscribeMethod信息。有了這些就可以反射調用實例的指定method方法了。
如何進行線程的切換?
在EventBus中會保存一個ThreadLocal實例,通過這個實例就能獲取到當前線程的信息PostingThreadState,在這個線程狀態信息中維護了很多信息,其中有個就是List集合隊列,裏面就是這個線程post 的所有信息。然後開啓一個while循環不斷的去post消息,post的過程中就是獲取這個object的所有相關類(父類和接口),遍歷根據class從subscriptionsByEventType緩存中找到對應的Subscription。根據subscription.subscriberMethod.threadMode 調用對應的線程切換方法。如果 post方法是在子線程 ,那麼會先把消息放到一個隊列中然後通過handler發送消息,開啓while循環,不停的invokeSubscriber

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章