前情概要

  在上一篇中,介绍了EventBus的基本使用方法,以及一部分进阶技巧。本篇及以后的几篇blog将会集中解析EventBus.java,看看作者是如何优雅地实现这个看似简单的事件分发/接收机制。

本篇概述

  剖析register的过程,let's get started!

方法签名

  完整的register方法签名如下,我们通常调用的register(this)其实最终调用到的register(this, false, 0),另外,使用registerSticky(this)进行调用,其实最终也是走到同一个方法中。

private synchronized void register(Object subscriber, boolean sticky, int priority) {
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
  • 声明为synchronized,是因为其中调用的subscribe方法需要在同步块中执行;
  • 这个register方法其实只做了一件事:将目标class的所有onEvent方法取出(通过反射),逐一对事件订阅(通过subscribe)

  subscribe翻译过来就是“订阅、订购”,是本次重点解析的内容,下面来揭开她神秘的面纱:

subscribe/订阅

  对于熟悉Design Patterns的人来说,第一眼看到EventBus,脑海中浮现的一定是观察者模式/Observer,这个模式的实现方式,无非就是——事件的分发者拥有一个订阅者的列表,每次事件发生时,分发者遍历并通知列表中的订阅者。订阅者可以自由地加入/退出订阅列表。

  register是一个订阅的过程,故在subscribe中所做的无非就是“将目标类的目标方法加入到订阅者列表”这件事。让我们结合代码来看。

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
Class<?> eventType = subscriberMethod.eventType;
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
} // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true); int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
subscriptions.add(i, newSubscription);
break;
}
} List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType); if (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);
}
}
}

  Event是分发者/订阅者解耦的关键,两者就是通过Event的class进行通信的。故先取出目标Event的订阅列表(subscriptionsByEventType),将新规则加入进去,如果重复register则会抛出Exception。加入的过程中,会根据优先级决定插入到List中的位置(int值越大,位置越靠前,优先级也就越高)。接下来还会将subscriber(也就是目标class)与新的eventType的对应关系加入到typesBySubscriber中,这个Map在后续的查找中会用到。

  对于sticky的的情况,若该eventBus支持事件继承(eventInheritance == true),则将eventType及其祖先类的所有Event都重新分发一遍,若不支持则只分发目标eventType。(此时分发的Event皆来自于stickyEvents

unregister/注销

  本篇最后分析一下注销的过程,代码很简单。

public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}

  unregister时,首先将eventtype - subscriber的绑定关系逐一解除(处理subscriptionsByEventType),最后把subscriber - eventTypes解绑。

下期预告

  剖析post过程

[EventBus源码解析] EventBus.register 方法详述的更多相关文章

  1. [EventBus源码解析] EventBus.post 方法详述

    前情概要 上一篇blog我们了解了EventBus中register/unregister的过程,对EventBus如何实现观察者模式有了基本的认识.今天我们来看一下它是如何分发一个特定事件的,即po ...

  2. EventBus源码解析 源码阅读记录

    EventBus源码阅读记录 repo地址: greenrobot/EventBus EventBus的构造 双重加锁的单例. static volatile EventBus defaultInst ...

  3. 【Android】EventBus 源码解析

    EventBus 源码解析 本文为 Android 开源项目实现原理解析 中 EventBus 部分项目地址:EventBus,分析的版本:ccc2771,Demo 地址:EventBus Demo分 ...

  4. Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean

    Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean 七千字长文深刻解读,Spirng中是如何初始化单例bean的,和面试中最常问的Sprin ...

  5. Android EventBus源码解析 带你深入理解EventBus

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:[张鸿洋的博客] 上一篇带大家初步了解了EventBus ...

  6. 源码解析-EventBus

    示例使用 时序图 源码解读 EventBus 使用 官网定义:EventBus 是一个使用 Java 写的观察者模式,解耦的 Android 开源库.EventBus 只需要几行代码即可解耦简化代码, ...

  7. 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  8. [Java多线程]-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

  9. EventBus源码解析

    用例 本文主要按照如下例子展开: //1. 新建bus对象,默认仅能在主线程上对消息进行调度 Bus bus = new Bus(); // maybe singleton //2. 新建类A(sub ...

随机推荐

  1. Jenkins快速上手

    一.Jenkins下载安装 1.到官网下载jenkins.war包:http://jenkins-ci.org/ 2.安装方法有两种: a) 把下载下来的jenkins.war包放到文件夹下,如C:\ ...

  2. Java学习指南学习笔记

    1, Java是一种静态类型.动态绑定的语言.具体来说,每一个对象都是编译时确定的良好类型.同时,可以在运行时检查一个对象究竟是什么. 2, Java中除了基本数字类型之外,Java中所有的对象都是通 ...

  3. RoseRT 建模学习

    目录: 一.RoseRT理论知识 二.一个完整模型的建立 三.TD-SCDMA(UE侧)RRC层建模的学习 四.LTE的RRC层建模(1.自主完成‘2.也可以是L2) 五.参考文献 一.RoseRT理 ...

  4. 团队开发——冲刺2.a

    冲刺阶段二(第一天) 1.今天准备做什么? 收集游戏图片:开始.暂停.继续.重新开始.退出……为了界面的后期美工做准备. 2.遇到什么困难? 网上的图片很多,但是比较难找到统一风格的.

  5. flask开发遇到 Must provide secret_key to use csrf解决办法

    开发flask的时候,遇到了 Must provide secret_key to use csrf错误提醒.原来是没有设置secret_key .在代码中加上 app.config['SECRET_ ...

  6. sqlite3使用(一)

    最近工作接触到sqlite3了,于是用博客记录下,当然只是浅用哈! 参考资料:http://www.runoob.com/sqlite/sqlite-tutorial.html 概念: SQLite ...

  7. 讨论贴:在sp_executesql 中生成的临时表的可见性

    首先创建数据表 IF object_id('TestTable') IS NOT NULL DROP TABLE TestTable GO ,),Info )) GO INSERT TestTable ...

  8. Monte Carlo Approximations

    准备总结几篇关于 Markov Chain Monte Carlo 的笔记. 本系列笔记主要译自A Gentle Introduction to Markov Chain Monte Carlo (M ...

  9. 新冲刺Sprint3(第一天)

    一.Sprint介绍 sprint2已经结束了,现在准备进行新一轮的冲刺--sprint3.现在简单说下sprint3的情况,正在进行的有更新商品图片和浏览商家相关信息,还有就是APP测滑栏的完善.准 ...

  10. 2016年中国大学生程序设计竞赛(合肥)-重现赛1009 HDU 5969

    最大的位或 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submi ...