前言
EventBus是一種發(fā)布-訂閱事件總線。它有三大要素:Event:事件、Publisher:發(fā)布者,可以在任意線程發(fā)布事件、Subscrible:訂閱者。
下面就讓從注冊開始慢慢揭開EventBus的神秘面紗。
EventBus.getDefault().register(this);
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
追蹤getDefault方法,我們可以清楚的看到它是通過雙重判空創(chuàng)建了一個EventBus對象,我們繼續(xù)往下追
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
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;
}
在初始化中創(chuàng)建了部分的參數(shù),我們下面會著重分析下subscriptionsByEventType、typesBySubscriber 、stickyEvents 。簡單介紹下它們:
subscriptionsByEventType:以event(即事件類)為key,以訂閱列表(Subscription)為value,事件發(fā)送之后,在這里尋找訂閱者,而Subscription又是一個CopyOnWriteArrayList,這是一個線程安全的容器。你們看會好奇,Subscription到底是什么?Subscription其實是一個封裝類,封裝了訂閱者、訂閱方法這兩個類。源碼中會一一說明。
typesBySubscriber:以訂閱者類為key,以event事件類為value,在進行register或unregister操作的時候,會操作這個map。
stickyEvents:保存的是粘性事件。
追到這里我們的EventBus的初始化就結束了,接著我們分析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);
}
}
}
從代碼中不難看出它是先獲取了訂閱者類的class,接著交給SubscriberMethodFinder的findSubscriberMethods()方法處理,返回結果保存在List中,由此可推測通過上面的方法把訂閱方法找出來了,并保存在集合中,那么我們直接看SubscriberMethodFinder的findSubscriberMethods()這個方法。
findSubscriberMethods
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//這里判斷條件用到了ignoreGeneratedIndex,從初始化那里我們得知默認值是false
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//重點,默認執(zhí)行的是findUsingInfo
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;
}
}
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;
...省略
}
繼續(xù)往下追,
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);
}
用到了FindState這個內(nèi)部類來保存訂閱者類的信息,我們看看它的內(nèi)部結構:
static class FindState {
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
...省略
}
我們可以看到這里當init的時候會對subscriberInfo置空,因此在findUsingInfo里面,會直接調(diào)用findUsingReflectionInSingleClass,這個方法非常重要?。。≡谶@個方法內(nèi)部,利用反射的方式,對訂閱者類進行掃描,找出訂閱方法,并用上面的Map進行保存,我們來看下這個方法。
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();
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
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");
}
}
}
雖然該方法比較長,但是邏輯非常清晰,逐一判斷訂閱者類是否存在訂閱方法,如果符合要求,并且調(diào)用FindState的checkAdd方法返回true的時候,才會把方法保存在findState的subscriberMethods內(nèi)。而SubscriberMethod則是用于保存訂閱方法的一個類。由上面代碼我們就知道了該類下的訂閱方法都被添加到了我們findState的subscriberMethods中,接著看findUsingInfo的返回,即getMethodsAndRelease方法。
getMethodsAndRelease
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;
}
它就是返回的findState的subscriberMethods。至此我們EventBus的register中findSubscriberMethods分析完畢,我們獲取到了注冊類的訂閱的方法以及訂閱的事件也都保存了下來。
然后就是分析register的subscribe()了:
subscribe
在該方法內(nèi),主要是實現(xiàn)訂閱方法與事件直接的關聯(lián),即放進我們上面提到關鍵的幾個Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents。
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
//將subscriber和subscriberMethod封裝成 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根據(jù)事件類型獲取特定的 Subscription
//Arraylist效率高,但線程不安全,在多線程的情況下,使用CopyOnWriteArrayList,避免多線程并發(fā)異常
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//如果為null,說明該subscriber尚未注冊該事件
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果不為null,并且包含了這個subscription 那么說明該subscriber已經(jīng)注冊了該事件,拋出異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//根據(jù)優(yōu)先級來設置放進subscriptions的位置,優(yōu)先級高的會先被通知
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;
}
}
//根據(jù)subscriber(訂閱者)來獲取它的所有訂閱事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
//把訂閱者、事件放進typesBySubscriber這個Map中
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 {
//根據(jù)eventType,從stickyEvents列表中獲取特定的事件
Object stickyEvent = stickyEvents.get(eventType);
//分發(fā)事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
到目前為止,注冊流程基本分析完畢,而關于最后的粘性事件的處理,這里暫時不說,下面會詳細進行講述。
注銷
與注冊相對應的是注銷,當訂閱者不再需要事件的時候,我們要注銷這個訂閱者,即調(diào)用以下代碼:
EventBus.getDefault().unregister(this);
直接上源碼分析:
public synchronized void unregister(Object subscriber) {
//根據(jù)當前的訂閱者來獲取它所訂閱的所有事件
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍歷所有訂閱的事件
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//從typesBySubscriber中移除該訂閱者
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
追下去unsubscribeByEventType:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根據(jù)事件類型從subscriptionsByEventType中獲取相應的 subscriptions 集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍歷所有的subscriptions,逐一移除
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
可以清楚的看到,上面兩個方法的邏輯就是從typesBySubscriber或subscriptionsByEventType移除相應與訂閱者有關的信息。是不是感覺注銷流程相對于注冊流程簡單了很多,其實注冊流程更多的分析處理集中于怎樣找到訂閱方法上。
發(fā)送事件
分析完了注冊和注銷,接著我們繼續(xù)探究下發(fā)送事件。用過的都知道發(fā)送有兩種一種是post一種是postSticky,我們先從post分析:
/** Posts the given event to the event bus. */
public void post(Object event) {
//獲取了PostingThreadState對象,內(nèi)部封裝了消息隊列、當前線程的信息、以及訂閱者、訂閱事件等。(currentPostingThreadState是一個ThreadLocal<PostingThreadState>)
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
//先將事件加入到隊列中
eventQueue.add(event);
if (!postingState.isPosting) {
//判斷當前線程是否是主線程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
//只要隊列不為空,就不斷從隊列中獲取事件進行分發(fā)
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
邏輯非常清晰,首先是獲取一個PostingThreadState(內(nèi)部封裝了消息隊列、當前線程的信息、以及訂閱者、訂閱事件等),然后將事件添加到它的eventQueue中,再往下就是一個while循環(huán),這里不斷地從隊列中取出事件,并且分發(fā)出去,調(diào)用的是EventBus的postSingleEvent方法。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//該eventInheritance上面有提到,默認為true,即EventBus會考慮事件的繼承樹
//如果事件繼承自父類,那么父類也會作為事件被發(fā)送
if (eventInheritance) {
//向上遍歷找到該類以及該類的所有父類(直到Object)
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);
}
//如果沒找到訂閱該事件的訂閱者
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));
}
}
}
從上述源碼中我們可以得到:當發(fā)送一個事件時,我們默認會將它和它的父類一起發(fā)送給訂閱者,接著調(diào)用了EventBus的postSingleEventForEventType,把事件、postingState、事件的類傳遞進去,那么我們來看看這個方法。
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//從subscriptionsByEventType獲取響應的subscriptions
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;
}
//...
}
return true;
}
return false;
}
接著追一下postToSubscription。
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 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);
}
}
首先獲取threadMode,即訂閱方法運行的線程,如果是POSTING(發(fā)送者是什么線程就在什么線程處理),那么直接調(diào)用invokeSubscriber()方法即可,如果是MAIN(不管發(fā)送者是什么線程,需要切到主線程處理),則要判斷當前線程是否是MAIN線程,如果是也是直接調(diào)用invokeSubscriber()方法,否則會交給mainThreadPoster來處理,其他情況相類似。幾個Poster的最后也都是調(diào)用invokeSubscriber(),而EventBus中invokeSubscriber方法的實現(xiàn)也很簡單,主要實現(xiàn)了利用反射的方式來調(diào)用訂閱方法,這樣就實現(xiàn)了事件發(fā)送給訂閱者,訂閱者調(diào)用訂閱方法這一過程。如下所示:
mainThreadPoster的handleMessage
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
//重點看這里
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
BackgroundPoster的run
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
//重點看這里
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
AsyncPoster的run
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
//重點看這里
eventBus.invokeSubscriber(pendingPost);
}
EventBus的invokeSubscriber
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);
}
}
postSticky的分析
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
postSticky也是最終調(diào)用的post,只是區(qū)別是它在之前會先把事件塞到stickyEvents中。處理還是走的上述的一套流程,唯一的區(qū)別是:當sticky事件沒有從stickyEvents移除的話,后續(xù)注冊的Class在注冊中會接收處理sticky的事件,代碼在subscribe中有分析過,這邊就再截取部分帶著看一下吧。
if (subscriberMethod.sticky) {
//eventInheritance為默認false,所以走else
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 {
//讀取stickyEvents中的事件
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
checkPostStickyEventToSubscription
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, Looper.getMainLooper() == Looper.myLooper());
}
}
又回到了我們熟悉的postToSubscription方法。至此我們EventBus的分析完結?。。∮捎诒疚暮荛L,建議讀者可以追著源碼看著解讀,這樣能加深理解。最后,為堅持讀完本文的你點贊,謝謝你們的閱讀!