EventBus官方介绍为一个为Android系统优化的事件订阅总线,它不只能够很方便的在同线程中传递事件或者对象,还能够在不一样线程中实现事件或对象的传递,用法比较简单,能够很好地完成一些在原生系统中的Intent,Handler等能够完成的工做,在Android开发过程当中用途及其普遍。固然这里不介绍它的具体用法,只走源码,而后本身动手写一下加深映象。不少人都说用了观察者设计模式,若是非得要往上靠,只能说不是正常的观察者。固然咱们也不用太关注,你就认为它是反射加注解。若是你会 RXjava 也能够用 RxBus,或者本身用 RxJava 简单的封装一下也行。java
我给别人写的好几个项目都用了这个开源库,的确比较方便,能够减小不少没必要要的代码,可是也有某一些问题,就是可读性并非特别高,跨度有时仍是比较大,固然咱们能够采用规范来避免掉这些问题。git
分析源码其实有不少动机,好比:1. 开发中出现了一下问题,报错或者收不到事件;2. 想了解一下原理,想知道是怎么个流程;3. 针对性的学习,想吸收里面的养分,想仔细的学习思想。等等...... 咱们也能从 EventBus 里面学习到一些有用的知识:github
1. 以前学到的一些设计模式:享元设计模式,单例设计模式,模板设计模式......设计模式
2. 以前学到的一些基础知识:volatile 关键字,线程间的通讯安全,线程池的运用......缓存
3. 反射和注解的一些细节,反射的缓存,方法的修饰符,方法参数的反射......安全
4. 可以参考 EventBus 源码本身写一些项目库,像跨模块通讯框架,固然大公司像阿里这些都有开源的框架,还用本身写吗?其实有时实现方式根本不同,用他们的未必适合本身的运行时架构,其次有时实在是闲着没事干。bash
#####1.EventBus.register()markdown
public void register(Object subscriber) { // 首先得到class对象 Class<?> subscriberClass = subscriber.getClass(); // 经过 subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod // 里包含了这个方法的 Method 对象,以及未来响应订阅是在哪一个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优 // 先级 priority ,以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的全部 Subscriber 注解方法属性。 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { // 订阅 subscribe(subscriber, subscriberMethod); } } } List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { // 先从缓存里面读取,订阅者的 Class List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); if (subscriberMethods != null) { return subscriberMethods; } // ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex。 // ignoreGeneratedIndex的默认值为false,能够经过EventBusBuilder来设置它的值 if (ignoreGeneratedIndex) { // 利用反射来获取订阅类中全部订阅方法信息 subscriberMethods = findUsingReflection(subscriberClass); } else { // 从注解器生成的MyEventBusIndex类中得到订阅类的订阅方法信息 // 这个这里不说,能够去看看以前的编译时注解 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> findUsingReflection(Class<?> subscriberClass) { FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); while (findState.clazz != null) { // 寻找某个类中的全部事件响应方法 findUsingReflectionInSingleClass(findState); findState.moveToSuperclass(); //继续寻找当前类父类中注册的事件响应方法 } return getMethodsAndRelease(findState); } 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 循环全部方法 for (Method method : methods) { // 获取方法访问修饰符 int modifiers = method.getModifiers(); // 找到全部声明为 public 的方法 if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { Class<?>[] parameterTypes = method.getParameterTypes();// 获取参数的的 Class if (parameterTypes.length == 1) {// 只容许包含一个参数 Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); if (subscribeAnnotation != null) { // 获取事件的 Class ,也就是方法参数的 Class Class<?> eventType = parameterTypes[0]; // 检测添加 if (findState.checkAdd(method, eventType)) { // 获取 ThreadMode ThreadMode threadMode = subscribeAnnotation.threadMode(); // 往集合里面添加 SubscriberMethod ,解析方法注解全部的属性 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"); } } } 复制代码
先看下 findSubscriberMethods() 这个方法,会经过类对象的 class 去解析这个类中的全部 Subscribe 注解方法的全部属性值,一个注解方法对应一个 SubscriberMethod 对象,包括 threadMode,priority,sticky,eventType,methodString。该方法执行完毕以后应该是下面这张图,效果就将就一下吧:架构
// Must be called in synchronized block private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { // 获取方法参数的 class Class<?> eventType = subscriberMethod.eventType; // 建立一个 Subscription Subscription newSubscription = new Subscription(subscriber, subscriberMethod); // 获取订阅了此事件类的全部订阅者信息列表 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) { // 线程安全的 ArrayList 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(); for (int i = 0; i <= size; i++) { if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription); break; } } // 经过 subscriber 获取 List<Class<?>> List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, 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>). 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); } } } 复制代码
接下来看下 subscribe 这个方法,这个相对来讲就简单许多了,把 subscriber , SubscriberMethod 分别存好,到底怎么存,这个时候看下面这两个集合:框架
// subscriptionsByEventType 这个集合存放的是?
// key 是 Event 参数的类
// value 存放的是 Subscription 的集合列表
// Subscription 包含两个属性,一个是 subscriber 订阅者(反射执行对象),一个是 SubscriberMethod 注解方法的全部属性参数值
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// typesBySubscriber 这个集合存放的是?
// key 是全部的订阅者
// value 是全部订阅者里面方法的参数的 class,eventType
private final Map<Object, List<Class<?>>> typesBySubscriber;
复制代码
#####2.EventBus.post()
/** Posts the given event to the event bus. */ public void post(Object event) { // currentPostingThreadState 是一个 ThreadLocal, // 他的特色是获取当前线程一份独有的变量数据,不受其余线程影响。 // 这个在 Handler 里面有过源码分析 PostingThreadState postingState = currentPostingThreadState.get(); // postingState 就是获取到的线程独有的变量数据 List<Object> eventQueue = postingState.eventQueue; // 把 post 的事件添加到事件队列 eventQueue.add(event); // 若是没有处在事件发布状态,那么开始发送事件并一直保持发布状态 if (!postingState.isPosting) { // 是不是主线程 postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); // isPosting = true postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { 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 Class<?> eventClass = event.getClass(); // 是否找到订阅者 boolean subscriptionFound = false; // 若是支持事件继承,默认为支持 if (eventInheritance) { // 查找 eventClass 的全部父类和接口 List<Class<?>> eventTypes = lookupAllEventTypes(eventClass); int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { Class<?> clazz = eventTypes.get(h); // 依次向 eventClass 的父类或接口的订阅方法发送事件 // 只要有一个事件发送成功,返回 true ,那么 subscriptionFound 就为 true subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); } } else { // 发送事件 subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); } // 若是没有订阅者 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 boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) { CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { // 获得Subscription 列表 subscriptions = subscriptionsByEventType.get(eventClass); } if (subscriptions != null && !subscriptions.isEmpty()) { // 遍历 subscriptions 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); } } 复制代码
到这里咱们基本就把核心的内容解析完了,重点就是去遍历 typesBySubscriber 找出知足需求的而后反射执行对应的方法,至于在哪里执行这个就须要判断 threadMode。
#####3.EventBus.unregister()
/** Unregisters the given subscriber from all event classes. */ public synchronized void unregister(Object subscriber) { // 获取订阅对象的全部订阅事件类列表 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. */ private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { // 获取事件类的全部订阅信息列表,将订阅信息从订阅信息集合中移除,同时将订阅信息中的active属性置为FALSE 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) { // 将订阅信息激活状态置为FALSE subscription.active = false; // 将订阅信息从集合中移除 subscriptions.remove(i); i--; size--; } } } } 复制代码
全部分享大纲:Android进阶之旅 - 系统架构篇
视频讲解地址:http://pan.baidu.com/s/1sl6wvBf