使用過程略過滑燃。
源碼分析
register方法:
1、獲取注冊對象類型
2颓鲜、獲取對象的所有的訂閱方法的集合
3表窘、遍歷集合,執(zhí)行訂閱subscribe方法甜滨。
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
SubscriberMethod類包含訂閱方法的所有信息乐严,Method對象,參數(shù)類型费变,執(zhí)行的線程董虱,優(yōu)先級券躁,是否粘性
public class SubscriberMethod {
final Method method;//Method
final ThreadMode threadMode;//執(zhí)行的線程
final Class<?> eventType;//方法參數(shù)的EventType
final int priority;//優(yōu)先級
final boolean sticky;//是否粘性
/** Used for efficient comparison */
String methodString;//用于比較的字段
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;
}
......其他代碼省略
}
SubscriberMethod集合的獲取邏輯:
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
findSubscriberMethods實現(xiàn)
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;
}
}```
分為使用索引和忽略索引兩個方法的內容,使用索引的后面單獨了解既琴。忽略索引的邏輯,F(xiàn)indState查找?guī)椭惻葑臁@锩娴腸heckAll甫恩、checkAddWithMethodSignature、moveToSuperclass這三個方法很有趣酌予,使用的map.put返回“前任”邏輯磺箕,巧妙的實現(xiàn)了對象是否被添加過的判斷纹腌。
static class FindState {
//所有訂閱方法的集合
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//事件類型是已經存在的標識map
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//方法key和方法所屬的類組成的標識map
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
//產生方法key的builder
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;
}
boolean checkAdd(Method method, Class<?> eventType) {
// 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) {
//沒有添加,返回true
return true;
} else {
//已經添加了,判斷前一個添加的標識對象是不是方法對象
if (existing instanceof Method) {
//是否已經添加了
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// 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)) {
// 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;
}
}
void moveToSuperclass() {
if (skipSuperClasses) {
clazz = null;
} else {
clazz = clazz.getSuperclass();
String clazzName = clazz.getName();
/** Skip system classes, this just degrades performance. */
if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
clazz = null;
}
}
}
}```
findUsingReflection:將訂閱對象中所有打了標記的Subscribe的訂閱方法,全部添加到findState的subscriberMethods中滞磺,然后通過getMethodsAndRelease升薯,返回所有的訂閱方法集合,并且將findState的對象放回對象池击困。
查找方法集合后涎劈,返回EventBus執(zhí)行注冊的邏輯。
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}```
subscribe:
//添加到集合阅茶,并且按照優(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;
}
}```
這里用到有兩個Cache:
1蛛枚、subscriptionsByEventType=EventType:Subscriptions(subscriber+subscriberMethod)
2、typesBySubscriber=obj:EventTypes
通過事件脸哀,快速定位到訂閱者+訂閱方法對象蹦浦;通過訂閱者,獲取它所訂閱的所有事件類型集合撞蜂。
粘性事件下一章再說盲镶。
注冊到些為止。
unregister:通過typesBySubscriber獲取所有注冊的事件類型蝌诡。然后通過subscriptionsByEventType獲取每個事件類型對應該的訂閱器集合溉贿,遍歷每個訂閱器,判斷是否為當前對象浦旱,如果是宇色,移除。
post:先看PostingThreadState類用來說明當前執(zhí)行的線程事件的執(zhí)行狀態(tài)颁湖。
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();//為什么沒有用實現(xiàn)隊列的LinkedList呢宣蠕?
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}```
一個本地線程包裝器,把PostingThreadState包裝一下甥捺。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};```
執(zhí)行postSingleEvent里面有一個lookupAllEventTypes方法抢蚀,獲取事件參數(shù)對應的所有接口的類型。放到緩存eventTypesCache中涎永。
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
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;
}
}```
接下來是postSingleEventForEventType具體的發(fā)送事件邏輯思币。
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);
}```
里面的postToSubscription方法,根據(jù)訂閱方法指定的線程模式羡微,執(zhí)行相應的邏輯谷饿。
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;
}
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);
}
}```
invokeSubscriber方法就是反射執(zhí)行方法。
執(zhí)行過程:
將要發(fā)送的對象:PendingPost妈倔,還有隊列PendingPostQueue博投。
mainThread對應的執(zhí)行對象:HandlerPoster
void enqueue(Subscription subscription, Object event) {
//緩存獲取發(fā)送對象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//加入到執(zhí)行隊列里面
queue.enqueue(pendingPost);
//是否正在執(zhí)行
if (!handlerActive) {
handlerActive = true;
//發(fā)送主線程消息
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;//是否執(zhí)行超時
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:
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);
}
}
}
@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
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}```
這三個poster都是大同小異,獲取執(zhí)行隊列盯蝴。然后循環(huán)執(zhí)行毅哗。
接下分析一下粘性事件:事件A已經發(fā)送完畢听怕,然后注冊一個訂閱A的粘性事件SB,那么立即還會向SB發(fā)送事件A虑绵∧虿t;谶@個邏輯分析,那么粘性事件一定是在注冊的時候翅睛。查看register的方法声搁。
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();
//如果注冊事件的類型在粘性事件的緩存里面執(zhí)行checkPostStickyEventToSubscription
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}```
checkPostStickyEventToSubscription最終執(zhí)行postToSubscription方法。
stickyEvents是在那里添加的呢捕发?EventBus并不是所有的事件都是粘性的疏旨,只有使用postSticky來發(fā)送的事件,才會被緩存下來扎酷。
接下來分析(兩個晚上檐涝,現(xiàn)在又到12:10分了,明天一定要弄完):索引的那部分邏輯法挨,知識比較多谁榜。
通過注解反身獲取訂閱對象的所有訂閱方法,會消耗一定的性能坷剧,所以EventBus在編譯期提供了生成代碼的邏輯惰爬,把注解的方法,統(tǒng)一生成代碼惫企。運行期直接注冊,就是我們將要分析的索引邏輯陵叽。
里面有一些元數(shù)據(jù)的概念狞尔,用來描述對象的屬性信息,各種info類巩掺,然后通過代碼MyEventBusIndex類(build里面)偏序。可以查看EventBusAnnotationProcessor代碼生成邏輯胖替。
參考:
http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html
http://www.reibang.com/p/f057c460c77e
http://kymjs.com/code/2015/12/12/01