EventBus源碼分析小結(jié)

1、EventBus.getDefault().register(this),getDefault()無非就是返回單例,所以直接看構(gòu)造:

   //subscriptionsByEventType,按事件類型訂閱,key為事件類型,也就是參數(shù)名,value為有這種事件類型的集合
   private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; 
   //typesBySubscriber,按訂閱者類型,key為訂閱者,value該訂閱者的事件類型
   private final Map<Object, List<Class<?>>> typesBySubscriber;
   private final Map<Class<?>, Object> stickyEvents;
   public EventBus() {
    this(DEFAULT_BUILDER);   //DEFAULT_BUILDER就是EventBusBuilder 
   }

   EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10); //Handler
    backgroundPoster = new BackgroundPoster(this);  //對應(yīng)background模式,實(shí)現(xiàn)了runnable
    asyncPoster = new AsyncPoster(this);  //對應(yīng)async模式
    indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
    subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
            builder.strictMethodVerification, builder.ignoreGeneratedIndex);  //見名只意,找訂閱者的方法
    logSubscriberExceptions = builder.logSubscriberExceptions;
    logNoSubscriberMessages = builder.logNoSubscriberMessages;
    sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
    sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
    throwSubscriberException = builder.throwSubscriberException;
    eventInheritance = builder.eventInheritance;
    executorService = builder.executorService;  //線程池
   }

接下來看register:

   public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    //尋找這個訂閱者方法,通過反射獲取方法遍歷判斷
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);  //這里是存儲信息
        }
    }
    }

看這個方法subscriberMethodFinder.findSubscriberMethods(subscriberClass):

   //返回這個訂閱者的方法集合
   List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {   //看有沒緩存,沒有再往下走
        return subscriberMethods;
    }

    if (ignoreGeneratedIndex) {  //默認(rèn)是false
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        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;
    }
    }

下面看下findUsingInfo:

   private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();  //用來存儲尋找過程的信息
    findState.initForSubscriber(subscriberClass);   //給findState.clazz賦值
    while (findState.clazz != null) {
         //上一步的ignoreGeneratedIndex作用就是在這里,但默認(rèn)的為null,我的理解是用戶的預(yù)處理
        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();  //尋找父類,如果是Android原生的跳出循環(huán)
    }
    return getMethodsAndRelease(findState);
   }

findUsingReflectionInSingleClass(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();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();  //拿到方法的參數(shù)
            if (parameterTypes.length == 1) {  //是否是一個參數(shù)
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); //有沒注解
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                         //保存到FindState中
                        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");
        }
    }
    }

經(jīng)過上面的方法查找,滿足條件的方法信息會保存到FindState,那么回到上面的findUsingInfo最后的return getMethodsAndRelease(findState):

    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    findState.recycle();
    synchronized (FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (FIND_STATE_POOL[i] == null) {
                FIND_STATE_POOL[i] = findState;
                break;
            }
        }
    }
    return subscriberMethods;
    }

上面就很簡單,返回的找到的符合的方法集合,到這里尋找訂閱者方法走完,回到register的subscribe:

   //參數(shù)一是訂閱者,二是訂閱者的方法
   private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;  //eventType是方法參數(shù)的類型
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);   
    if (subscriptions == null) {  //看有沒這種參數(shù)類型的集合
        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++) {   //優(yōu)先級比較
        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);
        }
    }
    }

2、注冊事件流程就到這里,總結(jié)一下,注冊流程會通過反射去找到訂閱者對應(yīng)的接收事件的方法,然后做相應(yīng)的保存,接下來看post流程:

   /** Posts the given event to the event bus. */
   public void post(Object event) {
    //currentPostingThreadState是ThreadLocal,線程互不干擾,拿到當(dāng)前線程的PostingThreadState 
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;  //當(dāng)前線程的事件隊列
    eventQueue.add(event);

    if (!postingState.isPosting) {   //是不是在發(fā)送
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        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;
        }
    }
   }

往下看 postSingleEvent:

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {  //Inheritance繼承的意思
        //尋找事件的父類與接口,比如我發(fā)送TextView,那么如果是View也會接收到
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass); 
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {  //遍歷發(fā)送
            Class<?> clazz = eventTypes.get(h);
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
   }

接著看postSingleEventForEventType:

   private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        subscriptions = subscriptionsByEventType.get(eventClass); //注冊的時候添加過
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted = false;
            try {   //賦值一些信息,開始發(fā)送
                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;
   }

再往下postToSubscription,分為四種模式:

   private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case POSTING:
            invokeSubscriber(subscription, event);  //最終調(diào)用method invoke來執(zhí)行訂閱者的方法
            break;
        case MAIN:
            if (isMainThread) {
                invokeSubscriber(subscription, event); //主線程直接執(zhí)行
            } else {
                mainThreadPoster.enqueue(subscription, event); //handler到主線程執(zhí)行
            }
            break;
        case BACKGROUND:
            if (isMainThread) {
                backgroundPoster.enqueue(subscription, event);  //主線程就交給線程池
            } else {
                invokeSubscriber(subscription, event);  //子線程直接運(yùn)行
            }
            break;
        case ASYNC:
            asyncPoster.enqueue(subscription, event);  //無論怎樣都交給線程池
            break;
        default:
            throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
    }
   }

總之,事件的傳遞最終都是通過反射invoke調(diào)用對應(yīng)訂閱者對應(yīng)的方法。從頭到尾總結(jié)下,注冊時,會通過反射找到這個訂閱者所有符合條件的方法并存儲起來,這里條件指的是注解和參數(shù),然后發(fā)送消息會遍歷存儲的訂閱者的信息,符合條件的通過反射直接調(diào)用對應(yīng)的方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容