EventBus原始碼學習

入魔的冬瓜發表於2019-04-24

看了別人的原始碼文章,一開始有點懵,還要複習下反射和註解器的知識。然後自己也做了下筆記,加深印象。

參考文章:

blog.csdn.net/u012933743/…

www.jianshu.com/p/c4d106419….

描述

EventBus是Android和Java的釋出/訂閱事件匯流排。

EventBus原始碼學習

優缺點:

  • 簡化了元件之間的通訊,將事件釋出者和訂閱者分離
  • 程式碼簡單
  • 包體積小缺點:利用反射,效能可能會差一點。可以使用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。

說說EventBus裡面用到的知識點

  • 註解處理器:

使用EventBus annotation processor(EventBus註解處理器),在編譯期間建立了訂閱者索引。(提升EventBus效能:greenrobot.org/eventbus/do…)。可以看到,會在build包下面生成一個EventBus的索引類。SUBSCRIBER_INDEX是一個Map型別資料,存放著每一個類裡面的註解資訊

EventBus原始碼學習

/** 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方法最後需要利用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集合。

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

複製程式碼

相關文章