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; }
然后是:
-
1 public void register(Object subscriber) { 2 if (subscriber == null) { 3 return; 4 } 5 synchronized (this) { 6 mMethodHunter.findSubcribeMethods(subscriber); 7 } 8 }
跟踪到mMethodHunter.findSubcribeMethods(subscriber);继续往下看:
mMethodHunter在代码头部注册:
-
1 /** 2 * the subscriber method hunter, find all of the subscriber's methods 3 * annotated with @Subcriber 4 */ 5 SubsciberMethodHunter mMethodHunter =newSubsciberMethodHunter(mSubcriberMap);
用于查找所有使用@subcriber的注解方法
然后我们跟到findSubcribeMethods(subscriber)里面看看:
遍历
-
1 public void findSubcribeMethods(Object subscriber) { 2 if (mSubcriberMap == null) { 3 throw new NullPointerException("the mSubcriberMap is null. "); 4 } 5 Class<?> clazz = subscriber.getClass(); 6 // 查找类中符合要求的注册方法,直到Object类 7 while (clazz != null && !isSystemCalss(clazz.getName())) { 8 final Method[] allMethods = clazz.getDeclaredMethods(); 9 for (int i = 0; i < allMethods.length; i++) { 10 Method method = allMethods[i]; 11 // 根据注解来解析函数 12 Subscriber annotation = method.getAnnotation(Subscriber.class); 13 if (annotation != null) { 14 // 获取方法参数 15 Class<?>[] paramsTypeClass = method.getParameterTypes(); 16 // 订阅函数只支持一个参数 17 if (paramsTypeClass != null && paramsTypeClass.length == 1) { 18 Class<?> paramType = convertType(paramsTypeClass[0]); 19 EventType eventType = new EventType(paramType, annotation.tag()); 20 TargetMethod subscribeMethod = new TargetMethod(method, eventType, 21 annotation.mode()); 22 subscibe(eventType, subscribeMethod, subscriber); 23 } 24 } 25 } // end for 26 // 获取父类,以继续查找父类中符合要求的方法 27 clazz = clazz.getSuperclass(); 28 } 29 }
然后再 subscibe(eventType, subscribeMethod, subscriber);方法里面的代码:
mSubcriberMap是个map集合
-
/** * the event bus's subscriber's map */ Map<EventType, CopyOnWriteArrayList<Subscription>> mSubcriberMap;
1 /** 2 * 按照EventType存储订阅者列表,这里的EventType就是事件类型,一个事件对应0到多个订阅者. 3 * 4 * @param event 事件 5 * @param method 订阅方法对象 6 * @param subscriber 订阅者 7 */ 8 private void subscibe(EventType event, TargetMethod method, Object subscriber) { 9 CopyOnWriteArrayList<Subscription> subscriptionLists = mSubcriberMap.get(event); 10 if (subscriptionLists == null) { 11 subscriptionLists = new CopyOnWriteArrayList<Subscription>(); 12 } 13 Subscription newSubscription = new Subscription(subscriber, method); 14 if (subscriptionLists.contains(newSubscription)) { 15 return; 16 } 17 subscriptionLists.add(newSubscription); 18 // 将事件类型key和订阅者信息存储到map中 19 mSubcriberMap.put(event, subscriptionLists); 20 }
到这里就可以看到register就是遍历所有注解@Subcriber的方法,并将事件类型key和订阅者信息存储在map中去。这点很类似eventbus代码中register,只不过eventbus是以以onEvent开头的方法去进行查找,而androideventbus是以@subcriber去进行遍历检索,但最终都是将事件类型key和订阅者信息存储在map中去。