面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>
1 简介
EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开发,Gihub地址是:EventBus。它简化了应用程序内各个组件之间进行通信的复杂度,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。
1.1 三个角色
- Event:事件,它可以是任意类型,EventBus会根据事件类型进行全局的通知。
- Subscriber:事件订阅者,在EventBus 3.0之前我们必须定义以onEvent开头的那几个方法,分别是
onEvent
、onEventMainThread
、onEventBackgroundThread
和onEventAsync
,而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe
,并且指定线程模型,默认是POSTING
。 - Publisher:事件的发布者,可以在任意线程里发布事件。一般情况下,使用
EventBus.getDefault()
就可以得到一个EventBus对象,然后再调用post(Object)
方法即可。
1.2 五种线程模型
EventBus3.0有五种线程模型,分别是:
四种模式分别是:POSTING、MAIN、MAIN_ORDERED、BACKGROUND、ASYNC。如果是想更新UI就使用MAIN模式,如果要进行耗时操作最好是使用ASYNC,因为这个模式能永远保证在不一样的线程中进行操作,而且都是子线程。
(1)POSTING:这种模式就是eventBus默认的模式,我们在使用的时候不需要再订阅者的方法的注解后面加任何东西(选择模式),但是这种只能在同一个线程中接收,也就是说,如果是在主线程中发布消息就只能在主线程中接收消息,如果是在子线程中,那么也只能在相同的子线程中去接收消息。如果非要声明POSTING的话,写法如下:
@Subscribe(threadMode = ThreadMode.POSTING)
public void showMsgFromSecondActivity(MessagePojo msg){
Log.i("test", ((String) msg.obj));
}
(2)MAIN:这种模式保证了订阅者指定的那个接收方法肯定要主线程中执行,可以放心的在里面执行更新UI操作。无论发布者是在主线程中还是在那一条子线程中发布消息,这边接收的都在主线程中。写法如下
@Subscribe(threadMode = ThreadMode.MAIN)
public void showMsgFromSecondActivity(MessagePojo msg){
Log.i("test", ((String) msg.obj));
}
(3)BACKGROUND:这种模式无论发布者是在主线程或者是那一条子线程中发布消息,接收函数的肯定是在子线程中,并且是这样理解:如果是在主线程中发布消息,那么就会随机开辟一条子线程来接收消息。如果是在子线程中发布消息,那么就会在相同的子线程来接收消息。写法如下:
@Subscribe(threadMode = ThreadMode.BACKGROUDN)
public void showMsgFromSecondActivity(MessagePojo msg){
Log.i("test", ((String) msg.obj));
}
(4)ASYNC:这种模式是无论你在那个线程中发布消息都会在不同的线程中接受消息。如果你在主线程中发布消息,就会随机的开辟一条子线程来接收消息;如果是在子线程中发布消息,就会开辟一条不同的子线程来接收消息。写法如下:
@Subscribe(threadMode = ThreadMode.ASYNC)
public void showMsgFromSecondActivity(MessagePojo msg){
Log.i("test", ((String) msg.obj));
}
(5) MAIN_ORDERED:这种模式在Android上,将在Android的主线程(UI线程)中调用订阅者。 与MAIN不同,该事件将始终排队等待发送。 这可确保后置调用是非阻塞的。
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onMessageEventMainOrdered(MessageEvent event) {
Log.i(TAG, "onMessageEventMainOrdered(), current thread is " + Thread.currentThread().getName());
}
1.3 使用场景
- 用于线程间的通讯代替handler或用于组件间的通讯代替Intent
- 广泛用于团购,商城,社交等应用,比如易大师APP,易宸锋Application...
- 实践证明已经有一亿多的APP中集成了EventBus
1.4 优势
- 简化了组件间的通讯。
- 分离了事件的发送者和接受者。
- 在Activity、Fragment和线程中表现良好。
- 避免了复杂的和易错的依赖关系和生命周期问题。
- 使得代码更简洁,性能更好。
- 更快,更小(约50k的jar包)。
2 EventBus 使用
2.1 引入依赖
在使用之前先要引入如下依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
2.2 定义事件
然后,我们定义一个事件的封装对象。在程序内部就使用该对象作为通信的信息:
public class MessageWrap {
public final String message;
public static MessageWrap getInstance(String message) {
return new MessageWrap(message);
}
private MessageWrap(String message) {
this.message = message;
}
}
2.3 发布事件
然后,我们定义一个Activity:
@Route(path = BaseConstants.LIBRARY_EVENT_BUS_ACTIVITY)
public class EventBusActivity extends CommonActivity<ActivityEventBus1Binding> {
@Override
protected void doCreateView(Bundle savedInstanceState) {
// 为按钮添加添加单击事件
getBinding().btnReg.setOnClickListener(v -> EventBus.getDefault().register(this));
getBinding().btnNav2.setOnClickListener( v ->
ARouter.getInstance()
.build(BaseConstants.LIBRARY_EVENT_BUS_ACTIVITY2)
.navigation());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onGetMessage(MessageWrap message) {
getBinding().tvMessage.setText(message.message);
}
}
这里我们当按下按钮的时候向EventBus注册监听,然后按下另一个按钮的时候跳转到拎一个Activity,并在另一个Activity发布我们输入的事件。在上面的Activity中,我们会添加一个监听的方法,即onGetMessage
,这里我们需要为其加入注解Subscribe
并指定线程模型为主线程MAIN
。最后,就是在Activity的onDestroy
方法中取消注册该Activity。
下面是另一个Activity的定义,在这个Activity中,我们当按下按钮的时候从EditText中取出内容并进行发布,然后我们退出到之前的Activity,以测试是否正确监听到发布的内容。
@Route(path = BaseConstants.LIBRARY_EVENT_BUS_ACTIVITY2)
public class EventBusActivity2 extends CommonActivity<ActivityEventBus2Binding> {
@Override
protected void doCreateView(Bundle savedInstanceState) {
getBinding().btnPublish.setOnClickListener(v -> publishContent());
}
private void publishContent() {
String msg = getBinding().etMessage.getText().toString();
EventBus.getDefault().post(MessageWrap.getInstance(msg));
ToastUtils.makeToast("Published : " + msg);
}
}
根据测试的结果,我们的确成功地接收到了发送的信息。
2.4 黏性事件
所谓的黏性事件,就是指发送了该事件之后再订阅者依然能够接收到的事件。使用黏性事件的时候有两个地方需要做些修改。一个是订阅事件的地方,这里我们在先打开的Activity中注册监听黏性事件:
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onGetStickyEvent(MessageWrap message) {
String txt = "Sticky event: " + message.message;
getBinding().tvStickyMessage.setText(txt);
}
另一个是发布事件的地方,这里我们在新的开的Activity中发布黏性事件。即调用EventBus的postSticky
方法来发布事件:
private void publishStickyontent() {
String msg = getBinding().etMessage.getText().toString();
EventBus.getDefault().postSticky(MessageWrap.getInstance(msg));
ToastUtils.makeToast("Published : " + msg);
}
按照上面的模式,我们先在第一个Activity中打开第二个Activity,然后在第二个Activity中发布黏性事件,并回到第一个Activity注册EventBus。根据测试结果,当按下注册按钮的时候,会立即触发上面的订阅方法从而获取到了黏性事件。
2.5 优先级
在Subscribe
注解中总共有3个参数,上面我们用到了其中的两个,这里我们使用以下第三个参数,即priority
。它用来指定订阅方法的优先级,是一个整数类型的值,默认是0,值越大表示优先级越大。在某个事件被发布出来的时候,优先级较高的订阅方法会首先接受到事件。
为了对优先级进行测试,这里我们需要对上面的代码进行一些修改。这里,我们使用一个布尔类型的变量来判断是否应该取消事件的分发。我们在一个较高优先级的方法中通过该布尔值进行判断,如果未true
就停止该事件的继续分发,从而通过低优先级的订阅方法无法获取到事件来证明优先级较高的订阅方法率先获取到了事件。
这里有几个地方需要注意:
- 只有当两个订阅方法使用相同的
ThreadMode
参数的时候,它们的优先级才会与priority
指定的值一致; - 只有当某个订阅方法的
ThreadMode
参数为POSTING
的时候,它才能停止该事件的继续分发。
所以,根据以上的内容,我们需要对代码做如下的调整:
// 用来判断是否需要停止事件的继续分发
private boolean stopDelivery = false;
@Override
protected void doCreateView(Bundle savedInstanceState) {
// ...
getBinding().btnStop.setOnClickListener(v -> stopDelivery = true);
}
@Subscribe(threadMode = ThreadMode.POSTING, priority = 0)
public void onGetMessage(MessageWrap message) {
getBinding().tvMessage.setText(message.message);
}
// 订阅方法,需要与上面的方法的threadMode一致,并且优先级略高
@Subscribe(threadMode = ThreadMode.POSTING, sticky = true, priority = 1)
public void onGetStickyEvent(MessageWrap message) {
String txt = "Sticky event: " + message.message;
getBinding().tvStickyMessage.setText(txt);
if (stopDelivery) {
// 终止事件的继续分发
EventBus.getDefault().cancelEventDelivery(message);
}
}
即我们在之前的代码之上增加了一个按钮,用来将stopDelivery
的值置为true
。该字段随后将会被用来判断是否要终止事件的继续分发,因为我们需要在代码中停止事件的继续分发,所以,我们需要将上面的两个订阅方法的threadMode
的值都置为ThreadMode.POSTING
。
按照,上面的测试方式,首先我们在当前的Activity注册监听,然后跳转到另一个Activity,发布事件并返回。第一次的时候,这里的两个订阅方法都会被触发。然后,我们按下停止分发的按钮,并再次执行上面的逻辑,此时只有优先级较高的方法获取到了事件并将该事件终止。
3 源代码分析
3.1目录结构
3.2 注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.POSTING;
/**
如果为true,Sticky事件只指事件消费者在事件发布之后才注册的也能接收到该事件的特殊类型。Android中就有这样的实例,也就是Sticky Broadcast,即粘性广播。正常情况下如果发送者发送了某个广播,而接收者在这个广播发送后才注册自己的Receiver,这时接收者便 无法接收到刚才的广播,为此Android引入了StickyBroadcast,在广播发送结束后会保存刚刚发送的广播(Intent),这样当接收者注册完Receiver 后就可以接收到刚才已经发布的广播。这就使得我们可以预先处理一些事件,让有消费者时再把这些事件投递给消费者。
*/
boolean sticky() default false;
/**
最后一个参数是priority,Method的优先级,优先级高的可以先获得分发的事件。这个不会影响不同的ThreadMode的分发事件顺序。
*/
int priority() default 0;
}
RetentionPolicy枚举三个属性值
1、SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
2、CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
3 RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
这3个生命周期分别对应于:Java源文件(.java文件) —> .class文件 —> 内存中的字节码。
那怎么来选择合适的注解生命周期呢?
首先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。
Target({ElementType.METHOD}) 表示适用于方法
ThreadMode 是enum(枚举)类型,threadMode默认值是POSTING。ThreadMode有四种模式,参考简介1.2 四中线程模式
3.3 EventBus实例
static volatile EventBus defaultInstance;
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
单例模式,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例。
volatile****关键字在java并发编程中常用,比synchronized的开销成本要小,轻便。作用是线程能访问共享变量,什么是共享变量呢?共享变量包括所有的实例变量,静态变量和数组元素,他们都存放在堆内存中。
3.4 EventBus的构造方法
它的构造方法并没有设置成私有的,注解我们看到,每一个EventBus都是独立地、处理它们自己的事件,因此可以存在多个EventBus,而通过getDefault()方法获取的实例,则是它已经帮我们构建好的EventBus,是单例,无论在什么时候通过这个方法获取的实例都是同一个实例。除此之外,我们可以通过建造者帮我们建造具有不同功能的EventBus。
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
//后面是一些表示开关信息的boolean值以及一个线程池
}
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;
subscriptionsByEventType:以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者,而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器。Subscription是一个封装类,封装了订阅者、订阅方法这两个类。
typesBySubscriber:以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个map。订阅者与该订阅者所订阅事件的集合关联。
stickyEvents:保存的是粘性事件。
3.5 register(this)注册
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
- 首先得到订阅者的Class对象
- findSubscriberMethods找出一个SubscriberMethod的集合,也就是传进来的订阅者所有的订阅的方法,把订阅方法找出来了,并保存在集合中。
- 接下来遍历订阅者的订阅方法来完成订阅者的订阅操作。对于SubscriberMethod(订阅方法)类中,主要就是用保存订阅方法的Method对象、线程模式、事件类型、优先级、是否是粘性事件等属性。
3.5.1 findSubscriberMethods()方法
SubscriberMethodFinder#findSubscriberMethods()方法具体实现:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//从缓存中获取SubscriberMethod集合
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex
if (ignoreGeneratedIndex) {
//通过反射获取subscriberMethods
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
//在获得subscriberMethods以后,如果订阅者中不存在@Subscribe注解并且为public的订阅方法,则会抛出异常。
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;
}
}
3.5.2 findSubscriberMethods()
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//从缓存中获取SubscriberMethod集合
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex
if (ignoreGeneratedIndex) {
//通过反射获取subscriberMethods
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
//在获得subscriberMethods以后,如果订阅者中不存在@Subscribe注解并且为public的订阅方法,则会抛出异常。
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;
}
}
- 首先从缓存中查找,如果找到了就立马返回。
- ignoreGeneratedIndex是否忽略注解器生成的MyEventBusIndex, ignoreGeneratedIndex在EventBusBuilder中默认为false,所以调用findUsingInfo()查找集合。
- 在获得subscriberMethods以后,如果订阅者中不存在@Subscribe注解且为public的订阅方法,则会抛出异常。
- 最后,找到订阅方法后,放入缓存,以免下次继续查找。ignoreGeneratedIndex 默认就是false,可以通过EventBusBuilder来设置它的值。我们在项目中经常通过EventBus单例模式来获取默认的EventBus对象,也就是ignoreGeneratedIndex为false的情况
关于对MyEventBusIndex不熟悉的,参考http://www.cnblogs.com/bugly/p/5475034.html
3.5.3 findUsingInfo()方法具体实现:
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//后面解释
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//获取订阅者信息,没有配置MyEventBusIndex返回null
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
//通过反射来查找订阅方法
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
- 首先创建和初始化FindState对象,它保存了一些订阅者的方法以及对订阅方法的校验。
- 如果我们通过EventBusBuilder配置了MyEventBusIndex,便会获取到subscriberInfo,调用subscriberInfo的getSubscriberMethods方法便可以得到订阅方法相关的信息,这个时候就不在需要通过注解进行获取订阅方法。 getSubscriberInfo(findState) ,一开始会返回null。
- 接着调用findUsingReflectionInSingleClass(findState);通过反射找到订阅方法。
3.5.4 findUsingReflectionInSingleClass方法具体实现(筛选):
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
//调用getDeclaredMethods方法输出的是自身的public、protected、private方法。
// This is faster than getMethods, especially when subscribers are fat classes like Activities
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
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) {//表明methods的参数只能有一个
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
//SubscriberMethod封装订阅方法
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
}
}
}
}
在这里主要是使用了Java的反射和对注解的解析。首先通过反射来获取订阅者中所有的方法。并根据方法的类型,参数和注解来找到订阅方法。找到订阅方法后将订阅方法相关信息保存到FindState当中。到这里便完成对订阅者中所有订阅方法的查找。
FindState#checkAdd方法返回true的时候,才会把方法保存在findState的subscriberMethods内。而SubscriberMethod则是用于保存订阅方法的一个类。
3.5.5 checkAdd()
FindState#checkAdd具体实现:
boolean checkAdd(Method method, Class<?> eventType) {
// 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
// Usually a subscriber doesn't have methods listening to the same event type.
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// Paranoia check
throw new IllegalStateException();
}
// Put any non-Method object to "consume" the existing Method
anyMethodByEventType.put(eventType, this);
}
return checkAddWithMethodSignature(method, eventType);
}
}
- 这个涉及到两层检查,第一层判断有无method监听此eventType,首先通过anyMethodByEventType.put(eventType, method) 将eventType以及method放进anyMethodByEventType这个Map中,同时该put方法会返回同一个key的上一个value值,所以如果之前没有别的方法订阅了该事件,那么existing应该为null,可以直接返回true.
- 第二层检查,checkAddWithMethodSignature通过MethodSignature(方法签名)判断能否把找到的method加进去。
3.5.6 checkAddWithMethodSignature()
FindState#checkAddWithMethodSignature()具体实现:
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
//methodKey由方法名与事件名组成
String methodKey = methodKeyBuilder.toString();
//获取当前方法所在的类的类名
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
} else {
// Revert the put, old class is further down the class hierarchy
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
eventType:表示方法的参数类型
该方法首先获取了当前方法的methodKey、methodClass等,并赋值给subscriberClassByMethodKey,如果方法签名相同,那么返回旧值给methodClassOld,接着是一个if判断,判断methodClassOld是否为空,由于第一次调用该方法的时候methodClassOld肯定是null,此时就可以直接返回true了。
再看看methodClassOld.isAssignableFrom(methodClass)这个方法,这个的意思是:methodClassOld是否是methodClass的父类或者同一个类。如果这两个条件都不满足,则会返回false,那么当前方法就不会添加为订阅方法了。
在findUsingReflectionInSingleClass中,经过一系列的对Method遍历,执行findState.subscriberMethods.add(),到这里便完成对订阅者中所有订阅方法的查找。最后会在List<SubscriberMethod> findUsingInfo()方法中调用getMethodsAndRelease()返回List<SubscriberMethod>。
3.5.7 getMethodsAndRelease()
看SubscriberMethodFinder#getMethodsAndRelease方法:
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
从findState获取subscriberMethods,放进新的ArrayList。
3.5.8 prepareFindState()
SubscriberMethodFinder#prepareFindState方法具体实现:
private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new FindState();
}
这是个复用池。第一次prepareFindState时,FIND_STATE_POOL[i]全不是null,有了一个state之后把相应的FIND_STATE_POOL[i]的引用变为null,这是为了防止并发编程时造成相互干扰。用完了这个state之后,recycle下面的for循环,会找到一个引用为null的FIND_STATE_POOL[i],并把自身引用赋给他。这样在并发的时候,这个复用池的效果就出来了:用的时候隔离开,用完了放回去。
- register注册入口
- findSubscriberMethods(subscriberClass),寻找订阅者类的订阅方法入口,参数为订阅者类
- 默认情况下,执行findUsingInfo(subscriberClass),会使用FindState作为中间变量,存储一些订阅者类信息,保存找到的订阅方法。
- findUsingReflectionInSingleClass(FindState findState),上面初始化好的FindState作为参数传递进来,通过反射,找到该订阅者所有的方法,筛选出符合条件的方法即为订阅方法,调用new SubscriberMethod(method, eventType, threadMode,subscribeAnnotation.priority(), subscribeAnnotation.sticky())封装订阅方法的各种信息,其中eventType为订阅方法的参数 也叫事件。通过findState把List<ScriberMethod>返回函数
- 遍历List<ScriberMethod>,调用new Subscription(subscriber, subscriberMethod),将订阅者和封装好的订阅方法再组合一起,根据订阅方法的优先级存入CopyOnWriteArrayList<Subscription>,最后调用subscriptionsByEventType.put(eventType, subscriptions),以事件类型为key,存储所有Subscription
- typesBySubscriber.put(subscriber, subscribedEvents); 再以订阅者为Key,存储该订阅者类中所有订阅事件。
- 最后处理粘性事件,暂时不考虑
- register流程完毕.
3.6 subscribe订阅
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//获取订阅方法的参数类型(订阅事件)
Class<?> eventType = subscriberMethod.eventType;
//订阅者和订阅方法 封装成Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//获取当前订阅事件中Subscription的List集合
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//如果为null,说明该subscriber尚未注册该事件
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//订阅者已经注册则抛出EventBusException
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//根据优先级来设置放进subscriptions的位置,优先级高的会先被通知
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<?>> 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);
}
}
}
- 首先会根据subscriber和subscriberMethod来创建一个Subscription对象。
- subscriptionsByEventType 用来处理 eventType订阅事件(参数类型) -> Subscription列表的映射,可以根据EventType订阅事件,找出该订阅者中的所有订阅方法。
- typesBySubscriber用来处理 subscriber(订阅者) -> eventType列表的映射,可以根据subscriber(订阅者),找出该订阅者中的所有订阅事件。
Subscription一个很重要的封装类:作用主要保存 订阅者和订阅方法
Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}
3.7 post事件分发.
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
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;
}
}
}
currentPostingThreadState 是一个ThreadLocal变量,即线程本地变量,不同线程之间不会相互影响。
1. 首先获取当前线程的postingState,得到当前线程的消息队列,将当前事件event加入到队列中。
2. 判断是否是在主线程post,设置标志位,调用postSingleEvent进行分发。
EventBus#PostingThreadState 内部类的实现:
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>();//当前线程的事件队列
boolean isPosting;//是否有事件正在分发
boolean isMainThread;//post的线程是否是主线程
Subscription subscription;//订阅者
Object event;//订阅事件
boolean canceled;//是否取消
}
该PostingThreadState主要是封装了当前线程的信息,以及订阅者、订阅事件等。
通过currentPostingThreadState.get()来获取PostingThreadState:
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,而这段数据是不会与其他线程共享的。
可以看出currentPostingThreadState的实现是一个包含了PostingThreadState的ThreadLocal对象,这样可以保证取到的都是自己线程对应的数据。
postSingleEvent(()
EventBus#postSingleEvent 方法:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
//如果没找到订阅该事件的订阅者
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
eventInheritance表示是否向上查找事件的父类,它的默认值为true,可以通过在EventBusBuilder中来进行配置。
当eventInheritance为true时,则通过lookupAllEventTypes找到所有的父类事件并存在List中,然后通过postSingleEventForEventType方法对事件逐一处理。
postSingleEventForEventType() 方法
EventBus#postSingleEventForEventType() 方法
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
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;
}
CopyOnWriteArrayList是为了线程安全,每次对List的修改都会重新一份,由于是线程安全的所以不需要同步处理,但是对HashMap的读取操作则不是线程安全的,所以需要线程同步。
1. 首先获取event(订阅事件)映射的subscriptions列表。
2. 遍历subscriptions,将event和subscription(包含订阅者和订阅方法)赋值到postingState对应成员变量中,调用postToSubscription进行分发。
postToSubscription 方法
EventBus#postToSubscription 方法:
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 MAIN_ORDERED:
if (mainThreadPoster != null) {
mainThreadPoster.enqueue(subscription, event);
} else {
// temporary: technically not correct as poster not decoupled from subscriber
invokeSubscriber(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);
}
}
invokeSubscriber方法主要是通过订阅方法的反射来执行。
mainThreadPoster主要是使用消息队列的形式Handler分发。下一篇文章分析。
在这里取出订阅方法的线程模式,之后根据订阅方法所设置的线程模式来选择线程来执行订阅方法的线程。 isMainThread表示发送Post的线程。
以下根据订阅方法的线程模式分类:
- POSTING:默认的 ThreadMode,表示在执行 Post 操作的线程直接调用订阅者的事件响应方法,
不论该线程是否为主线程(UI 线程)。直接调用invokeSubscriber()。
- MAIN:如果post是在MainThread则直接调用上面的方法;如果不是则向mainThreadPoster加入队列。mainThreadPoster类型是HandlerPoster,其继承自Handler。也即是通过Handler将订阅方法切换到主线程执行。
- BACKGROUND:订阅方法在后台线程,如果Post操作在主线程,则通过backgroundPoster加入队列。
- ASYNC:发布线程是否为主线程,都使用一个空闲线程来处理。不使用队列管理多个事件,也不管发布者处在主线程与否,为每一个事件单独开辟一个线程处理.
流程图
事件分发流程总结:
- 首先获取当前线程的PostingThreadState对象从而获取到当前线程的事件队列,每调用一次Post方法,就往该队列加入时事件。
- postSingleEvent(eventQueue.remove(0), postingState),默认情况下,遍历一个事件类型的所有父类和接口,
- subscriptionsByEventType,通过事件类型获取到所有订阅者集合
- 通过反射执行订阅者中的订阅方法
3.8注销
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 {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
获取订阅者的所有订阅的事件类型
从事件类型的订阅者集合中移除订阅者
unsubscribeByEventType方法实现:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
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) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
先根据事件类型获取所有subscriptionsByEventType注册的订阅者和订阅方法
找出要注销的订阅者,移除该订阅者中的所有订阅方法。
4其他
4.1官方文档
http://greenrobot.org/files/eventbus/javadoc/3.0/