零蚀
🔗 前言
🔗 Android 知识栈
🔗 Android 散装系列
🔗 NO.1 Handler->就这?
🔗 NO.2 Android 垃圾回收机制
🔗 NO.3 Android 测量、排版那点事
🔗 NO.4 项目无法一键打包?自己写个shell脚本吧
前言
-
为什么看EventBus
- 其实前几天并没有学习计划,这两天是比较放松的一天,大体任务都已经快要做完,现在的任务就是把TCP-IP的协议看完,然后看多线程,但是今天没有带书过来(也不想看电子书),所以今天就是空闲的一天,今天趁自己有点时间,来看看EventBus的内部构造。毕竟很多人多已经看过它如何实现,我怎么能错过。
-
步骤
- 这次不准备看使用方法了,我觉得轮子,不知道使用方法,就不知道也没什么大不了,使用时想知道,去看看文档好了,所以我觉得没有写案例的价值,与其把精力放在多方便(量变)上,不如多关注那些能(质变)事物,当然这样看源码大部分也算不上多有意义,大多只是敷衍一下社会需求。
EventBus源码
-
注册相关
- register方法
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }
- 我们可以看到这里有个
findSubscriberMethods
方法,这个方法作用和它的名字一样,它是通过你传入的类(Class)来查找你这个类中被订阅的方法。我们可以顺着这个代码继续向下看。
for (Method method : methods) { int modifiers = method.getModifiers(); if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); if (subscribeAnnotation != null) { 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())); } } .....
-
我们可以看到,这里的他会在你这个
subscriberClass
中,通过反射,然后遍历这个类其中的所有的方法,看看有没有方法是被Subscribe
的注解修饰过,当他找到后会将方法的信息参数保存在findState.subscriberMethods
中,然后我们看看SubscriberMethod
是什么,它其实里面就是一个方法的所有信息,在EventBus中所用到的信息,比如threadMode(线程),eventType(事件类型),priority(优先级),sticky(粘性)。看到这里,我们不难发现,我们常用的用于定义接受信息的方法设置,这里基本都有了。 -
值得一提的是这里有一个
methodString
属性,而且注释明确写了不用Method的比较方法(equal),为什么不是使用方法(Method)自带的equal的比较方法,而是用String的equal(hashCode)方式来进行比较,其实跟着看了一下,这里主要的问题在于“性能”,如果是Method.equal可能要花费0.6秒左右的时间,这对手机来说绝对是不能容忍的。 -
回到我们的register方法,然后就开始进入了
subscribe
,订阅主要是做什么的,他其实就是对eventType
进行一些处理,他的处理逻辑如下。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class<?> eventType = subscriberMethod.eventType; Subscription newSubscription = new Subscription(subscriber, subscriberMethod); CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) { 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; } } 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); } } }
- 他会根据,你这个事件的优先级先排个序,然后再将这些事件分类,如class作为key,事件列表作为value保存在一个map中,最后对粘滞事件做出对应的处理,如果是粘滞事件,在获取到这个事件列表之后,会根据类别进行使用,这也就是粘滞事件异步操作的原理。
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); } }
-
发送消息
- 发送消息
/** Posts the given event to the event bus. */ public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); 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 { while (!eventQueue.isEmpty()) { postSingleEvent(eventQueue.remove(0), postingState); } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }
-
其实到这里我们就可看出来,这里的post就是将消息加入了一个自己定义的list队列里面,然后如果队列不是空的,它就会使用
postSingleEvent
轮训的将消息发送出来。post方法就是这么简单。 -
说了这么多,我们来看一下发送消息的逻辑,怎么发送消息的呢。我们可以先看看
EventBus getDefault()
/** Convenience singleton for apps using a process-wide EventBus instance. */ public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }
- 我们在使用
EventBus.getDefault()
时候这里创建了一个单例对象。然后这里构建了熟悉的属性,这些属性其实在之前的postToSubscription
发送消息的方法里面进行了使用,这些属性其实就是一个Handler和一些Runnable,到这里你是不是心里就都明白了。
- 他会根据具体的情况,来选择是用反射还是handler来发送消息,从而触发那些被订阅的方法。