1,分析androidEventbus的注册源代码:
我们在使用androidEventbus的第一步是注册eventbus,如下代码:
EventBus.getDefault().register(this);
首先获取eventbus对象,采用单利模式实现获取对象:
Eventbus.java里面
-
public static EventBus getDefault() {
if (sDefaultBus == null) {
synchronized (EventBus.class) {
if (sDefaultBus == null) {
sDefaultBus = new EventBus();
}
}
}
return sDefaultBus;
}
然后是:
-
public void register(Object subscriber) {
if (subscriber == null) {
return;
}
synchronized (this) {
mMethodHunter.findSubcribeMethods(subscriber);
}
}
跟踪到mMethodHunter.findSubcribeMethods(subscriber);继续往下看:
mMethodHunter在代码头部注册:
/**
* the subscriber method hunter, find all of the subscriber's methods
* annotated with @Subcriber
*/
SubsciberMethodHunter mMethodHunter =newSubsciberMethodHunter(mSubcriberMap);
用于查找所有使用@subcriber的注解方法
然后我们跟到findSubcribeMethods(subscriber)里面看看:
遍历
-
public void findSubcribeMethods(Object subscriber) {
if (mSubcriberMap == null) {
throw new NullPointerException("the mSubcriberMap is null. ");
}
Class<?> clazz = subscriber.getClass();
// 查找类中符合要求的注册方法,直到Object类
while (clazz != null && !isSystemCalss(clazz.getName())) {
final Method[] allMethods = clazz.getDeclaredMethods();
for (int i = 0; i < allMethods.length; i++) {
Method method = allMethods[i];
// 根据注解来解析函数
Subscriber annotation = method.getAnnotation(Subscriber.class);
if (annotation != null) {
// 获取方法参数
Class<?>[] paramsTypeClass = method.getParameterTypes();
// 订阅函数只支持一个参数
if (paramsTypeClass != null && paramsTypeClass.length == 1) {
Class<?> paramType = convertType(paramsTypeClass[0]);
EventType eventType = new EventType(paramType, annotation.tag());
TargetMethod subscribeMethod = new TargetMethod(method, eventType,
annotation.mode());
subscibe(eventType, subscribeMethod, subscriber);
}
}
} // end for
// 获取父类,以继续查找父类中符合要求的方法
clazz = clazz.getSuperclass();
}
}
然后再 subscibe(eventType, subscribeMethod, subscriber);方法里面的代码:
mSubcriberMap是个map集合
-
/**
* the event bus's subscriber's map
*/
Map<EventType, CopyOnWriteArrayList<Subscription>> mSubcriberMap;/**
* 按照EventType存储订阅者列表,这里的EventType就是事件类型,一个事件对应0到多个订阅者.
*
* @param event 事件
* @param method 订阅方法对象
* @param subscriber 订阅者
*/
private void subscibe(EventType event, TargetMethod method, Object subscriber) {
CopyOnWriteArrayList<Subscription> subscriptionLists = mSubcriberMap.get(event);
if (subscriptionLists == null) {
subscriptionLists = new CopyOnWriteArrayList<Subscription>();
}
Subscription newSubscription = new Subscription(subscriber, method);
if (subscriptionLists.contains(newSubscription)) {
return;
}
subscriptionLists.add(newSubscription);
// 将事件类型key和订阅者信息存储到map中
mSubcriberMap.put(event, subscriptionLists);
}
到这里就可以看到register就是遍历所有注解@Subcriber的方法,并将事件类型key和订阅者信息存储在map中去。这点很类似eventbus代码中register,只不过eventbus是以以onEvent开头的方法去进行查找,而androideventbus是以@subcriber去进行遍历检索,但最终都是将事件类型key和订阅者信息存储在map中去。