EventBus源碼學習

看了別人的源碼文章,一開始有點懵,還要複習下反射和註解器的知識。而後本身也作了下筆記,加深印象。設計模式

參考文章:緩存

blog.csdn.net/u012933743/…安全

www.jianshu.com/p/c4d106419….bash

描述

EventBus是Android和Java的發佈/訂閱事件總線。數據結構

優缺點:

  • 簡化了組件之間的通訊,將事件發佈者和訂閱者分離
  • 代碼簡單
  • 包體積小缺點:利用反射,性能可能會差一點。可使用EventBus annotation processor(EventBus註解處理器),在編譯期間建立了訂閱者索引。(提高EventBus性能:greenrobot.org/eventbus/do…

三要素:

  • Event:自定義事件類型
  • Subscriber:事件訂閱者。在EventBus3.0以前咱們必須定義以onEvent開頭的那幾個方法,分別是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,而在3.0以後事件處理的方法名能夠隨意取,不過須要加上註解@subscribe(),而且指定線程模型,默認是POSTING。
  • Publisher:事件發佈者。能夠在任意線程裏發佈事件,通常狀況下,使用EventBus.getDefault()就能夠獲得一個EventBus對象,而後再調用post(Object)方法便可。

4個線程:

  • POSTING:在發佈線程的事件執行
  • MAIN:在主線程執行。
  • BACKGROUND:若是發佈事件的線程爲主線程則新建一個線程執行,不然在發佈事件的線程執行。
  • ASYNC:在新的線程執行

利用Handler切換到主線程。BACKGROUND線程,使用到了線程池ExecutorService。async

說說EventBus裏面用到的知識點

  • 註解處理器:

使用EventBus annotation processor(EventBus註解處理器),在編譯期間建立了訂閱者索引。(提高EventBus性能:greenrobot.org/eventbus/do…)。能夠看到,會在build包下面生成一個EventBus的索引類。SUBSCRIBER_INDEX是一個Map類型數據,存放着每個類裏面的註解信息ide

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(com.example.camera_learning.eventbus.EventBusActivity.class, true,
                new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEvent", com.example.camera_learning.eventbus.TestEvent.class),
            new SubscriberMethodInfo("onEvent", com.example.camera_learning.eventbus.TestEvent2.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

複製代碼
  • 反射

若是索引類中有緩存相關的註解信息的話,那就會直接用索引類裏面的註解信息。若是沒有的話,就須要利用反射去獲取類中的全部方法,而後拿到有@Subscribe的方法。post

post方法最後須要利用invoke來調用訂閱者對象的訂閱方法(具體代碼能夠看下面)性能

  • 設計模式:單例模式、建造者模式、觀察者模式
  • ThreadLocal:EventBus會經過ThreadLocal爲每一個線程維護一個PostingThreadState對象。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};

final static class PostingThreadState {
    //分發隊列
    final List<Object> eventQueue = new ArrayList<>();
    //是否正在分發
    boolean isPosting;
    //是不是主線程
    boolean isMainThread;
    //訂閱關係
    Subscription subscription;
    //當前正在分發的事件
    Object event;
    //是否取消
    boolean canceled;
}
複製代碼

EventBus裏面的一些數據結構

比較重要的就是下面兩個map集合。ui

//key爲事件類型,value值爲Subscription的集合。這樣能夠根據事件的類型,直接獲取訂閱該事件的全部類中的全部方法
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
//key爲訂閱對象,value爲該類中的全部訂閱事件類型的集合。
private final Map<Object, List<Class<?>>> typesBySubscriber;
//粘性事件
private final Map<Class<?>, Object> stickyEvents;

//Subscription類,表示一個訂閱關係,包含訂閱對象和訂閱方法
final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
}
複製代碼

閱讀源碼

getDefault()方法

  • 利用雙重校驗鎖實現單例模式,保證線程安全
  • 使用Builder建造者模式,將一個複雜對象的構建和它的表示分離。建造者模式通常用來建立複雜對象,用戶能夠不用關心其建造過程和細節。在EventBus中,指的是EventBusBuilder類,可使用自定義參數建立EventBus實例。
public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

public EventBus() {
    this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
    logger = builder.getLogger();
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    backgroundPoster = new BackgroundPoster(this);
    asyncPoster = new AsyncPoster(this);
    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;
}

public class EventBusBuilder {
    private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
    boolean logSubscriberExceptions = true;
    boolean logNoSubscriberMessages = true;
    boolean sendSubscriberExceptionEvent = true;
    boolean sendNoSubscriberEvent = true;
    boolean throwSubscriberException;
    boolean eventInheritance = true;
    boolean ignoreGeneratedIndex;
    boolean strictMethodVerification;
    ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
    List<Class<?>> skipMethodVerificationForClasses;
    List<SubscriberInfoIndex> subscriberInfoIndexes;
    Logger logger;
    MainThreadSupport mainThreadSupport;
    EventBusBuilder() {
    }

 /** Builds an EventBus based on the current configuration. */
public EventBus build() {
    return new EventBus(this);
}
複製代碼

register方法

register的最終目的是,將註解的信息保存到對應的map中。而獲取的過程,優先經過註解器生成的註解信息獲取,若是沒有的話,再利用反射獲取註解方法。

public void register(Object subscriber) {
    //拿到class對象
    Class<?> subscriberClass = subscriber.getClass();
    //利用SubscriberMethodFinder類來找出這個類中的全部訂閱方法
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    //拿到類中全部的訂閱方法後,調用subscribe方法
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

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


複製代碼

下面看一下SubscriberMethodFinder類。

//這個map對象,key值爲訂閱者類,value爲該類中的全部訂閱方法的list集合。已經register過的話,相應的數據已經在map中存在了,這個時候就能夠直接從map中讀取就好了,不用再次利用反射進行多餘的遍歷類中的方法。有點空間換時間的思想。
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

//經過這個方法,遍歷出某個類中的全部訂閱方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //根據緩存值,判斷是否註冊過EventBus
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //默認爲false,因此通常是先走findUsingInfo方法,經過自動生成的索引類好比MyEventBusIndex來獲取到被註解的辦法。這種辦法比經過findUsingReflection()利用反射去獲取方法的性能好一點。若是沒有獲取到索引中存儲的訂閱者Subscriber信息的話,纔去走利用反射的辦法。
    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    //若是訂閱者類和父類中,沒有@Subscribe利用監聽事件的方法,就會拋這個錯誤。
    if (subscriberMethods.isEmpty()) {
        throw new EventBusException("Subscriber " + subscriberClass
                + " and its super classes have no public methods with the @Subscribe annotation");
    } else {
        //獲取到訂閱者類中的全部註解方法後,保存到cache中
        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();
            //遍歷,檢查後,添加到list集合
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            //若是在索引類中找不到訂閱信息,那就經過反射的辦法來獲取
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

//在生成的索引類中,獲取保存的訂閱信息
private SubscriberInfo getSubscriberInfo(FindState findState) {
    if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
        SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
        if (findState.clazz == superclassInfo.getSubscriberClass()) {
            return superclassInfo;
        }
    }
    
    //若是subscriberInfoIndexes爲空,也就是沒有利用生成索引的辦法來提升EventBus性能,直接返回null
    //不爲空的話,遍歷,拿到這個訂閱類中的全部註解方法
    if (subscriberInfoIndexes != null) {
        for (SubscriberInfoIndex index : subscriberInfoIndexes) {
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}


//使用subscribe方法
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //訂閱方法的事件類型
    Class<?> eventType = subscriberMethod.eventType;
    //建立一個Subscription,包含訂閱類對象和訂閱方法
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //獲取到這種事件類型的list集合
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    
    if (subscriptions == null) {
        //保存到subscriptionsByEventType裏面,key爲事件類型,value爲Subscription
        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);
        }
    }
}




複製代碼

post方法

post方法最後會走到postSingleEventForEventType方法,拿到註冊這個事件的訂閱者信息,利用反射調用訂閱方法的執行。

public void post(Object event) {
    //獲取當前線程的PostingThreadState對象
    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 boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //去map集合中,根據事件類型,獲取到全部的訂閱方法
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        //遍歷訂閱該事件的list集合
        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);
    }
}


//最後是利用反射,調用訂閱者對象的訂閱方法
void invokeSubscriber(Subscription subscription, Object event) {
    try {
        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
    } catch (InvocationTargetException e) {
        handleSubscriberException(subscription, event, e.getCause());
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Unexpected exception", e);
    }
}



複製代碼

unregister方法

unregister方法就是要把這個類中的註解信息都給移除掉。

public synchronized void unregister(Object subscriber) {
    //獲取這個訂閱者種的全部訂閱事件類型list
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            //遍歷事件類型list,移除subscriptionsByEventType中包含這個訂閱者的全部訂閱關係
            unsubscribeByEventType(subscriber, eventType);
        }
        //移除這個訂閱對象
        typesBySubscriber.remove(subscriber);
    } else {
        logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

//移除subscriptionsByEventType中包含這個訂閱者的全部訂閱關係
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}

複製代碼
相關文章
相關標籤/搜索