前言
開篇要說聲sorry,限於各種原因,Okhttp的下篇和OKIO要delay 了,本週先來一個簡單一些的。
EventBus 是一個基於觀察者模式的事件釋出/訂閱框架,開發者可以通過極少的程式碼去實現多個模組之間的通訊,而不需要以層層傳遞介面的形式去單獨構建通訊橋樑。從而降低因多重回撥導致的模組間強耦合,同時避免產生大量內部類。其可以很好的應用於Activity之間,Fragment之間,後臺執行緒之間的通訊,避免使用intent或者handler所帶來的複雜度。其缺點則是可能會造成介面的膨脹。特別是當程式要求大量形式各異的通知,而沒有做出良好的抽象時,程式碼中會包含大量的介面,介面數量的增長又會帶來命名、註釋等等一大堆問題。本質上說觀察者要求從零開始實現事件的產生、分發與處理過程,這就要求參與者必須對整個通知過程有著良好的理解。當程式程式碼適量時,這是一個合理的要求,然而當程式太大時,這將成為一種負擔。
EventBus基於觀察者模式的Android事件分發匯流排。
EventBus基本使用
1.定義訊息事件MessageEvent,也就是建立事件型別
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
複製程式碼
2.註冊觀察者並訂閱事件
選擇要訂閱該事件的訂閱者(subscriber),Activity即在onCreate()加入,呼叫EventBus的register方法,註冊。
EventBus.getDefault().register(this);
複製程式碼
在不需要接收事件發生時可以
EventBus.getDefault().unregister(this);
複製程式碼
在訂閱者裡需要用註解關鍵字 @Subscribe
來告訴EventBus使用什麼方法處理event。
@Subscribe
public void onMessageEvent(MessageEvent event) {
Toast.makeText(this, event.message, Toast.LENGTH_SHORT).show();
}
複製程式碼
注意方法只能被public修飾,在EventBus3.0之後該方法名字就可以自由的取了,之前要求只能是onEvent().
3.傳送事件
通過EventBus的post方法,發出我們要傳遞的事件。
EventBus.getDefault().post(new MessageEvent("HelloEveryone"));
複製程式碼
這樣選擇的Activity就會接收到該事件,並且觸發onMessageEvent方法。
EventBus原始碼解析
瞭解了對於EventBus的基礎使用,解析來,我們針對其基礎使用的呼叫流程,來了解EventBus的實現流程和原始碼細節。
註冊觀察者
EventBus.getDefault().register(this);
複製程式碼
- getDefault()
EventBus.getDefault()是一個單例,實現如下:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
複製程式碼
保證了App單個程式中只會有一個EventBus例項。
- register(Object subscriber)
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
複製程式碼
register方法中,首先獲得訂閱例項的類,然後呼叫SubscriberMethodFinder例項的findSubscriberMethods
方法來找到該類中訂閱的相關方法,然後對這些方法呼叫訂閱方法。註冊的過程涉及到兩個問題,一個是如何查詢註冊方法?另一個是如何將這些方法進行儲存,方便後面的呼叫?
SubscriberMethodFinder是如何從例項中查詢到相關的註冊方法的呢?
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//根據類資訊叢快取中查詢訂閱方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//查詢註冊方法
if (ignoreGeneratedIndex) {
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;
}
}
複製程式碼
首先從快取的方法中,通過Class作為Key進行查詢,如何查詢內容為空,則會呼叫findUsingReflection或者findUsingInfo來從相關類中查詢,得到註冊的方法列表之後,將其新增到快取之中。
快取的資料結構如下:
Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
複製程式碼
訂閱方法
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) {
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);
}
}
}
複製程式碼
subscribe方法的執行流程是先根據事件型別,判斷該註冊者是否已經進行過註冊,如果未註冊將其中的方法進行儲存,以事件型別為鍵儲存一份,然後以註冊者例項為鍵儲存一份。
傳送事件
對於事件的傳送,呼叫的是post函式
- post(Object event)
public void post(Object event) {
//獲取當前執行緒的Event佇列,並將其新增到佇列中
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
//如果當前PostingThreadState不是在post 中
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
//遍歷事件佇列,呼叫postSingleEvent方法
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
複製程式碼
post方法中,首先從當前的PostingThreadState中獲取當前的事件佇列,然後將要post的事件新增到其中,之後判斷當前的執行緒是否處在post中,如果不在,那麼則會遍歷事件佇列,呼叫postSingleEvent
將其中的事件丟擲。
currentPostingThreadState是一個ThreadLocal型別的,裡面儲存了PostingThreadState。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
}
複製程式碼
PostingThreadState包含了一個eventQueue和一些標誌位。類具體結構如下。
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
複製程式碼
- postSingleEvent
postSingleEvent的具體實現如下。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
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) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
複製程式碼
通過lookupAllEventTypes(eventClass)
得到當前eventClass的Class,以及父類和介面的Class型別,而後逐個呼叫postSingleEventForEventType方法。事件派發的核心方法在postSingleEventForEventType方法中。
- 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 {
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;
}
複製程式碼
從subscriptionsByEventType中拿到訂閱了eventClass的訂閱者列表 ,遍歷,呼叫postToSubscription方法,逐個將事件丟擲。
- 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 MAIN_ORDERED:
if (mainThreadPoster != null) {
mainThreadPoster.enqueue(subscription, event);
} else {
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);
}
}
複製程式碼
根據threadMode去判斷應該在哪個執行緒去執行該方法,而invokeSubscriber方法內通過反射呼叫函式。
MainThread
首先去判斷當前如果是UI執行緒,則直接呼叫;否則, mainThreadPoster.enqueue(subscription, event) BackgroundThread
如果當前非UI執行緒,則直接呼叫;如果是UI執行緒,則呼叫backgroundPoster.enqueue方法。
Async
呼叫asyncPoster.enqueue方法
接下來會針對這幾種廣播方式展開分析
- 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);
}
}
複製程式碼
通過反射的方式,直接呼叫訂閱該事件方法。
- mainThreadPoster.enqueue
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
複製程式碼
mainThreadPoster 通過mainThreadSupport.createPoster建立。
public Poster createPoster(EventBus eventBus) {
return new HandlerPoster(eventBus, looper, 10);
}
複製程式碼
返回HandlerPoster例項。
通過Subscription和Event例項構造出PendingPost,然後將其加入到PendingPostQueue之中,然後呼叫sendMessage,其handleMessage函式將會被回撥。
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
複製程式碼
訊息處理
@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;
}
}
複製程式碼
當得到訊息之後,開啟迴圈,從佇列中取PendingPost,呼叫invokeSubscriber方法執行。
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
複製程式碼
這裡呼叫了releasePendingPost
static void releasePendingPost(PendingPost pendingPost) {
pendingPost.event = null;
pendingPost.subscription = null;
pendingPost.next = null;
synchronized (pendingPostPool) {
// Don't let the pool grow indefinitely
if (pendingPostPool.size() < 10000) {
pendingPostPool.add(pendingPost);
}
}
}
複製程式碼
為了避免物件的重複建立,在PendingPost中維護了一個PendingPost列表,方便進行物件的複用。
List<PendingPost> pendingPostPool = new ArrayList<PendingPost>();
複製程式碼
對於物件的建立,可以通過其obtainPendingPost方法來獲得。
- asyncPoster.enqueue
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
複製程式碼
將PendingPost新增到PendingPost佇列中,執行緒池會從佇列中取資料,然後執行。
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
複製程式碼
- backgroundPoster.enqueue
相比於asyncPoster,backgroundPoster可以保證新增進來的資料是順序執行的,通過同步鎖和訊號量的方式來保證,只有一個執行緒是在活躍從事件佇列中取事件,然後執行。
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
eventBus.getExecutorService().execute(this);
}
}
}
複製程式碼
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
}
} finally {
executorRunning = false;
}
}
複製程式碼
函式掃描
在register方法中對於訂閱方法的查詢,呼叫的方法是SubscriberMethodFinder的findSubscriberMethods方法,對於其中方法的查詢有兩種方式,一個是findUsingInfo
,一個是findUsingReflection
。
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
//獲取FindState例項
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
//從當前類中查詢,然後跳到其父類,繼續查詢相應方法
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
複製程式碼
首先,會獲得一個FindState例項,其用來儲存查詢過程中的一些中間變數和最後結果,首先找當前類中的註冊方法,然後跳到其父類之中,其父類會自動過濾掉Java,Android中的相應類,然後繼續查詢。
查詢的核心實現在方法findUsingReflectionInSingleClass中。
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// 獲取該類中的所有方法,不包括繼承的方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
//遍歷獲取的方法,判斷新增規則為是否為public函式,其引數是否只有一個,獲取其註解,然後呼叫checkAdd,
//在加入到訂閱方法之前
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)) {
//多於一個引數
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
//非public,abstract,非靜態的
}
}
}
複製程式碼
按照如下掃描規則,對類中的函式進行掃描
掃描規則:1.函式非靜態,抽象函式 2.函式為public;3.函式僅單個引數;4.函式擁有@Subscribe
的註解;
在符合了以上規則之後,還不能夠直接將其加入到函式的佇列之中,還需要對方法進行校驗。
boolean checkAdd(Method method, Class<?> eventType) {
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
throw new IllegalStateException();
}
anyMethodByEventType.put(eventType, this);
}
return checkAddWithMethodSignature(method, eventType);
}
}
//函式簽名校驗,來進行
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
} else {
// Revert the put, old class is further down the class hierarchy
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
複製程式碼
為掃描到的函式做校驗,在校驗後,釋放自己持有的資源。第一層校驗在checkAdd函式中,如果當前尚未有函式監聽過當前事件,就直接跳過第二層檢查。第二層檢查為完整的函式簽名的檢查,將函式名與監聽事件類名拼接作為函式簽名,如果當前subscriberClassByMethodKey
中不存在相同methodKey時,返回true,檢查結束;若存在相同methodKey時,說明子類重寫了父類的監聽函式,此時應當保留子類的監聽函式而忽略父類。由於掃描是由子類向父類的順序,故此時應當保留methodClassOld而忽略methodClass。
上述的方式是通過在執行期通過註解處理的方式進行的,效率是比較慢的,在EventBus最新版中引入了在編譯器通過註解處理器,在編譯器生成方法索引的方式進行,以此來提升效率。
粘性事件處理
粘性事件的設計初衷是,在事件的發出早於觀察者的註冊,EventBus將粘性事件儲存起來,在觀察者註冊後,將其發出。通過其內部的一個資料結構:
Map<Class<?>, Object> stickyEvents
複製程式碼
儲存每個Event型別的最近一次post出的event
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);
}
複製程式碼
將粘性事件儲存在stickyEvents,而後post出,此時如果存在已經註冊的觀察者,則情況同普通事件情況相同;如尚無註冊的觀察者,在postSingleEvent函式中將時間轉化為一個NoSubscriberEvent事件發出,可由EventBus消耗並處理。待觀察者註冊時,從stickyEvents中將事件取出,重新分發給註冊的觀察者。
if (subscriberMethod.sticky) {
if (eventInheritance) {
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);
}
}
複製程式碼
在對於粘性事件處理這段程式碼中,首先判斷是否監聽Event的子類,而後呼叫checkPostStickyEventToSubscription將黏性事件發出,在checkPostStickyEventToSubscription中,判空後按一半事件的post流程將事件傳遞給觀察者。
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
postToSubscription(newSubscription, stickyEvent, isMainThread());
}
}
複製程式碼
小結
輪子的每週一篇,已經到了第四周了,下週是對OkHttp的更細緻的一個剖析,然後是對於OkIO的剖析