EventBus 我們叫它事件總線,他能夠將之前我們一些複雜的功能簡單化,比如一個頁面發送數據,其他多個頁面也會收到消息,用它就比較方便和簡單,並且包也不大。
實現方式:
1.它是通過觀察者模式實現事件的傳遞,通過註冊事件(發佈者),反註冊事件(取消發佈),及註解標記方法(訂閱)來實現應用。
2.內部實現通過獲取訂閱方法的註解獲取配置信息並通過反射機制調用消費事件。
事件類型分爲兩種:
1.普通事件:普通事件必須先註冊,訂閱方法,然後才能收到發送的消息,基本流程是:
註冊並訂閱方法------> post消息-------> 訂閱方法收到消息(所有註冊過,並訂閱(添加Subscribe註解)的方法都會收到這條消息,這個與訂閱時是否設置 sticky 爲true或false無關。
2.粘性事件:粘性事件可以不用先註冊,當一條粘性消息發出時,我們來到下一個頁面通過訂閱(這時sticky必須爲true),並註冊了,這時就會收到先前發送的粘性事件,並且在我們收到粘性事件時如果不去調用remove 方法刪除粘性消息,那麼他會一直存在在消息集合中,當其他頁面訂閱註冊時還會收到消息,並且是所有註冊訂閱過的方法都會收到,當然,這在之前當post一條消息時,所有註冊過並訂閱過的方法都會收到該消息,與發送是post()和stickPost()無關,粘性事件基本流程是:
stickyPost消息------->訂閱(加Subscribe關鍵字方法)並註冊------->訂閱方法收到粘性事件就消息。注意,如果這時有多個頁面同時註冊和訂閱了事件,那麼他們都會收到該消息。
基本使用:我直接貼代碼了
//註冊事件
@Override
protected void onStart() {
super.onStart();
//註冊事件
EventBus.getDefault().register(this);
}
反註冊事件
@Override
protected void onDestroy() {
super.onDestroy();
//反註冊
EventBus.getDefault().unregister(this);
}
//訂閱事件,並且當前方法是在主線程中被調用的,sticky表示是否粘性事件
@Subscribe(threadMode = ThreadMode.MAIN,sticky = false)
public void onEventTest(Object msg){
Log.d(TAG, "onEvent: " + msg.toString());
EventBus.getDefault().removeStickyEvent(msg);
}
發送事件
EventBus.getDefault().post("普通事件");
EventBus.getDefault().postSticky("粘性事件");
特點:
1.當一個頁面已經註冊並且訂閱了事件,這時其他頁面,無論發送的是哪種發送方式,該頁面訂閱方法都會收到消息。
2.當一個頁面A訂閱和註冊了事件,先發送一條粘性事件,然後跳轉到頁面B但是它通過postStick發送事件,頁面B 註冊了並且訂閱了事件,且sticky=trur;這時A會先收到它發送的消息,然後B頁面也會收到消息。從A發送粘性事件到B 收到粘性事件,我們暫且叫做粘性事件的一個迴路。這也基本是粘性事件的最多使用點。
使用起來很多簡單,下面我們看源碼:
事件的註冊:
EventBus.getDefault().register(this);
getDefault 通過雙重鎖單例獲取了一個EventBus實例,這裏做了一些集合等的初始化動作。
public void register(Object subscriber) {
//獲取當前類的class對象
Class<?> subscriberClass = subscriber.getClass();
//獲取當前類中所有的訂閱方法封裝類SubscriberMethod 集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//循環調用訂閱
subscribe(subscriber, subscriberMethod);
}
}
}
SubscriberMethod 類是訂閱方法的一個封裝體,
1.保存了訂閱函數的方法對象method
2.保存了當前訂閱方法的註解信息,例如線程,是否粘性,優先級
3.保存了當前訂閱類的class對象
findSubscriberMethods 方法實現
METHOD_CACHE是一個map緩存器
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//通過clas 對像獲取方法封裝集合
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;
}
}
findUsingInfo 方法主要用於實現獲取方法封裝類的集合。
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//初始化對象池
FindState findState = prepareFindState();
//設置訂閱類class對象
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//這裏獲取到的值是空,通過上一步可知
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
//獲取SubscriberMethod 數組,當前類中
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();
}
//將findState中SubscriberMethod 集合取出
return getMethodsAndRelease(findState);
}
FindState 類也是一個方法信息類,並且創建了一個類工具池,大小是4個,部分類內容
static class FindState {
這個集合就是上邊我們要的返回的方法封裝集合
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
// 方法參數class 爲key 值爲方法函數 的map
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
// key 函數名和註冊類名拼接字串 value 訂閱函數methclass 的map
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
// 這個是用於拼接subscriberClassByMethodKey 的key 的StringBuilder,這裏沒有牽扯對多線程,所以用效率較高的StringBuilder
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;
}
// 回收內存,用於複用
void recycle() {
subscriberMethods.clear();
anyMethodByEventType.clear();
subscriberClassByMethodKey.clear();
methodKeyBuilder.setLength(0);
subscriberClass = null;
clazz = null;
skipSuperClasses = false;
subscriberInfo = null;
}
findUsingReflectionInSingleClass 方法組裝實現FindState類,其中有用到註解相關知識,如果不瞭解可以參考如何自定義一個註解並獲取註解
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
//反射獲取註冊類中所有方法返回methods 數組
//表示的類或接口聲明的所有方法,包括公共、保護、默認(包)訪問和私有方法,但不包括繼承的方法。當然也包括它所實現接口的方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
try {
//反射獲取註冊類中所有方法返回methods 數組
//返回某個類的所有公用(public)方法包括其繼承類的公用方法,當然也包括它所實現接口的方法。
methods = findState.clazz.getMethods();
} catch (LinkageError error) { // super class of NoClassDefFoundError to be a bit more broad...
String msg = "Could not inspect methods of " + findState.clazz.getName();
if (ignoreGeneratedIndex) {
msg += ". Please consider using EventBus annotation processor to avoid reflection.";
} else {
msg += ". Please make this class visible to EventBus annotation processor to avoid reflection.";
}
throw new EventBusException(msg, error);
}
findState.skipSuperClasses = true;
}
//遍歷所有方法
for (Method method : methods) {
// 獲取當前方法的修飾符
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//獲取該方法的參數類型,返回一個clase數組
Class<?>[] parameterTypes = method.getParameterTypes();
//參數至少要有一個否則會報異常
if (parameterTypes.length == 1) {
//獲取註解 訂閱信息 Subscribe類
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
//線程枚舉類型,決定了調用函數在那個線程工作
ThreadMode threadMode = subscribeAnnotation.threadMode();
//將符合條件的函數添加進findState中的subscriberMethods集合
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");
}
}
}
getMethodsAndRelease 方法主要是獲取 FindState 中 List<SubscriberMethod>
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
//獲取訂閱方法封裝類集合
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
//回收findState
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;
}
到此List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
執行完成了,我們拿到了subscriberMethods 也就是getMethodsAndRelease方法返回的集合。一般情況下集合只有一個方法,因爲多數情況我們在一個activity/Fragment 中只訂閱一個方法。
然後回到register 類
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { //遍歷當前類,調用subscribe 方法訂閱 for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }
在看subscribe前先了解些SubscriberMethod 構造函數參數
public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
//當前函數
this.method = method;
// 當前函數 運行線程
this.threadMode = threadMode;
//當前函數的參數類型
this.eventType = eventType;
// 優先級
this.priority = priority;
//是否粘性事件
this.sticky = sticky;
}
// Must be called in synchronized block
// subscriber 就是註冊類對象, subscriberMethod 是註冊類中一個訂閱方法封裝類
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//獲取訂閱函數參數類型
Class<?> eventType = subscriberMethod.eventType;
//Subscription 又對 就是註冊類對象 和註冊類中一個訂閱方法封裝類 進行封裝,並且重寫了equals 和 hashCode方法,
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//subscriptionsByEventType 用於存放訂閱方法封裝類的map key 是當前函數的參數類型,value是Subscription集合 ,key用於將相同函數參數類型的subscriptions 放到集合中
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();
//將當前subscriptions 對像放在集合的最後一位,例如現在集合中有兩條數據size=2,那麼就將新的放在下標爲2處。可見subscriptionsByEventType 設計的比較巧妙。
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);
}
//typesBySubscriber key爲訂閱類實例,value 是 List<Class<?>> 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>).
//遍歷粘性事件map stickyEvents
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);
}
}
}
newSubscription 是上邊我們說訂閱函數等的封裝類,stickyEvent 是要發送的事件消息
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, isMainThread());
}
}
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);
}
}
invokeSubscriber 是執行到的最終方法,調用了invoke 反射方法,調用了訂閱類並將參數傳進去,這時我們訂閱方法就會執行,並且是執行在我們設定的線程中的。如果對反射不瞭解可以參考java反射invoke方法的使用
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);
}
}
總結:這裏可以看到我們在註冊事件的過程中主要做了兩件事情,1.將訂閱的方法相關信息進行保存的過程。2.如果是粘性事件,同時查詢粘性map ,將map中的所有粘性消息通過訂閱方法發出,這就是整個消息註冊的過程。