本文發(fā)表于KuTear's Blog,轉(zhuǎn)載請注明
最簡單的例子說起
先從一個簡單的栗子出發(fā)掏呼,看看EventBus
的功能是什么碱妆。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
findViewById(R.id.say_hello).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().post(new EventBean(1,"Hello"));
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN) //在ui線程執(zhí)行
public void onEvent(EventBean event) {
System.out.println(Thread.currentThread().getName());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
上面的代碼是最簡單的一個事件懈息,當點擊按鈕之后回調(diào)onEvent()
方法罕扎。下面就著重看看這個過程的實現(xiàn)抵屿。類似的代碼我們見得很多庆锦,比如App存在一個UserManager
,有一個用戶狀態(tài)的分發(fā),很多類在這里注冊了用戶狀態(tài)的監(jiān)聽回調(diào)轧葛,當用戶登陸搂抒,所有的注冊了監(jiān)聽的類都會收到這個消息艇搀。其實EventBus
的實現(xiàn)也是類似的,只是不存在接口求晶。
看看上面的代碼中符,我們可能會對是怎樣回調(diào)onEvent()
感到一絲的困惑。下面進入源碼的世界誉帅。
EventBus 源碼分析
先看看一些有用的字段
//K->方法參數(shù)的類型 V->K的所有父類的結(jié)合(包括本身) 用作緩存
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
//K->方法參數(shù)的類型 V->所有參數(shù)類型的K的訂閱函數(shù)的集合 主要是消息發(fā)送使用
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
//K->注冊的類淀散,如Activity V-> 注冊類的注冊函數(shù)的參數(shù)的集合 主要是注冊/解綁使用
private final Map<Object, List<Class<?>>> typesBySubscriber;
//粘性事件 K->發(fā)出的事件的參數(shù)類型 V->事件的值
private final Map<Class<?>, Object> stickyEvents;
一切的開始-事件的訂閱
//EventBus
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
//獲取該類的所有的能接受事件的函數(shù),也就是上面說的`onEvent(...)`
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
如何才能找到注冊的方法呢,這就要看看SubscriberMethodFinder
的具體實現(xiàn)了.
//SubscriberMethodFinder
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//提升速度蚜锨,優(yōu)先重緩存中取,支持并發(fā)操作
//聲明為 Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) { //默認為false
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;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//從復用池中取回一個FindState
FindState findState = prepareFindState();
//為findState設(shè)置clazz等參數(shù)
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);
//通常為NULL
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);
}
//設(shè)置findState.clazz為剛剛clazz的父類
findState.moveToSuperclass();
}
//獲取findState.subscriberMethods
return getMethodsAndRelease(findState);
}
再看findUsingReflectionInSingleClass()
之前,線看看FindState
的一部分實現(xiàn)
//FindState
static class FindState {
//訂閱者的方法的列表
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//以EventType為key档插,method為value
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//以method的名字生成一個methodKey為key,該method的類(訂閱者)為value
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
//構(gòu)建methodKey的StringBuilder
final StringBuilder methodKeyBuilder = new StringBuilder(128);
//訂閱者
Class<?> subscriberClass;
//當前類
Class<?> clazz;
//是否跳過父類
boolean skipSuperClasses;
//SubscriberInfo
SubscriberInfo subscriberInfo;
void initForSubscriber(Class<?> subscriberClass) {
//clazz為當前類
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
boolean checkAdd(Method method, Class<?> eventType) { //帶檢測方法亚再,和他的參數(shù)類型
// 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
// Usually a subscriber doesn't have methods listening to the same event type.
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) { //檢測函數(shù)的簽名
// Paranoia check
throw new IllegalStateException();
}
// Put any non-Method object to "consume" the existing Method
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)) {
//判斷old是否為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;
}
}
}
Ok,下面看看findUsingReflectionInSingleClass()
的實現(xiàn)吧.
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(); //方法的修飾符 public|protected|private|default(package)
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { //大體上就是要求public,非static|abstract
Class<?>[] parameterTypes = method.getParameterTypes(); //獲取參數(shù)類型數(shù)組
if (parameterTypes.length == 1) { //只允許有一個參數(shù)
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) { //函數(shù)必須包含注解
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");
}
}
}
現(xiàn)在函數(shù)調(diào)用棧退回到了最開始的register()
,接著看subscribe(...)
方法。
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType; //參數(shù)類型
//將注冊類和方法打包為Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//同一個事件不再多次注冊氛悬,所以每次使用后一定要解綁则剃,不解綁還會內(nèi)存泄露
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++) {
//根據(jù)優(yōu)先級放入合適的位置
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
//typesBySubscriber K->注冊的類,如Activity V-> 注冊類的注冊函數(shù)的參數(shù)的集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
//注冊的時候判斷是否有粘性事件如捅,如有就執(zhí)行咯
if (subscriberMethod.sticky) {
if (eventInheritance) { //Default true
// 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();
//判斷eventType是否為candidateEventType的父類棍现,即所有的子類都能收到消息
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
//發(fā)送消息,這里先不講镜遣,在后面也會說的
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
上面注冊的過程基本已經(jīng)說完己肮,下面將講事件的發(fā)送過程。根據(jù)最上面的栗子悲关,我們知道入口是post()
函數(shù)谎僻,下面就入手post()
函數(shù)。
事件的發(fā)送
//保證每個線程取得的PostingThreadState不同寓辱,但是相同線程取得的相同艘绍,本質(zhì)就是HashMap<Thread,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<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
//添加到隊列
eventQueue.add(event);
//如果隊列沒有在分發(fā)事件就開始分發(fā)
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 {
//循環(huán)執(zhí)行分發(fā)
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass(); //事件參數(shù)類型
boolean subscriptionFound = false;
if (eventInheritance) { //default true
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);
}
//對錯誤的處理,可以自己注冊`NoSubscriberEvent`來捕獲
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));
}
}
}
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
//eventTypesCache K->事件參數(shù)的類型 V->K的所有父類的結(jié)合(包括本身)
//發(fā)送一個子類型的事件秫筏,父類型的也要求收到該事件
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
//遞歸添加所有的父類/接口
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
根據(jù)上面的代碼查看诱鞠,知道所有的事件發(fā)送都是通過函數(shù)postSingleEventForEventType()
發(fā)送。下面看看具體的實現(xiàn)跳昼。
/**
*
* @param event 事件數(shù)據(jù)
* @param postingState
* @param eventClass 事件參數(shù)類型
* @return
*/
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//subscriptionsByEventType K->方法參數(shù)的類型 V->所有參數(shù)類型的K的訂閱函數(shù)的集合
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;
}
/**
* @param subscription 訂閱者
* @param event 數(shù)據(jù)
* @param 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 = new HandlerPoster(this/*eventBus*/, Looper.getMainLooper(), 10);
// HandlerPoster extends Handler
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);
}
}
這里就是EventBus
對四種線程模式的不同處理般甲,這里只拿出其中一個來講肋乍。對于MAIN
鹅颊,如果當前POST
線程就是主線程,那么當然就是直接調(diào)對應(yīng)的函數(shù)就OK,如果當前POST
不是主線程墓造,那么就要用Handler
發(fā)送到主線程堪伍。下面看看實現(xiàn)锚烦。
void enqueue(Subscription subscription, Object event) {
//類似android源碼中的Message的獲取方式
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//待發(fā)送的消息加入隊列
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); //使用EventBus回調(diào)方法
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;
}
}
在EventBus
中,調(diào)用注冊的方法帝雇。
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
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);
}
}
可以看出涮俄,只是很簡單用反射調(diào)用了要調(diào)了方法,到此對普通事件的分析就完了尸闸,下面看看粘性事件彻亲。
//EventBus
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);
}
結(jié)合上面注冊的時候的代碼分析,我們知道postSticky()
的事件會在postSticky()
的時候發(fā)送一次吮廉,并在有新注冊粘性事件的時候會再次匹配,最后就是看看事件的解綁苞尝。
事件的解綁
/**
* Unregisters the given subscriber from all event classes.
*/
public synchronized void unregister(Object subscriber) {
//注冊類的注冊函數(shù)的參數(shù)的集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
/**
* Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber.
*
* @param subscriber 注冊類
* @param eventType 參數(shù)Type
*/
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//取得參數(shù)類型為eventType的所有注冊函數(shù)的集合
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--;
}
}
}
}
通過上面的代碼,可以看出宦芦,其實事件的移除就是把它重List
/HashMap
中remove
掉宙址。