总结
-
需要先通过register接口进行注册为订阅者,订阅方法才能生效,不再接收消息的时候主动调用 unregister取消注册,也避免内存泄漏(特别是一些有生命周期的activity等);
-
只有通过注释@Subscribe声明为订阅者方法(消息处理)才能接收EventBus接口发送的消息,并且要求必须是public,非sstatic,非abstract,而且入参数量只能是1个;
-
@Subscribe注释提供了3个属性字段:
3.1 threadMode: 指明订阅方法允许在哪个线程上,默认为;
3.2 sticky: 指明是否是粘性事件,默认false;
3.3 priority:指明订阅方法的优先级,越大优先级越高,默认为0;
-
threadMode目前支持:
4.1 POSTING : 运行在与事件发送方相同的线程上,堵塞执行;
4.2 MAIN : 运行在主线程,如果当前发送方式主线程,则立马堵塞并执行,否则进入排队等待主线程Handler执行;
4.3 MAIN_ORDERED :运行在主线程,与main的区别在于,MAIN_ORDERED都是排队执行,如果发送方当前是主线程的话,不会堵塞当前线程,而main则是如果当前是主线程会堵塞主线程直到订阅方法执行完毕;
4.4 BACKGROUND : 运行在后台线程,如果当前post发送方是主线程,进入后台线程排队,如果当前post发送方是后台线程,则直接堵塞该线程并执行;
4.5 ASYNC : 运行在异步线程,无论如何都另起线程来执行订阅方法,与post发送方所在线程不同,与BACKGROUND都是非主线程,但是async一定会另起线程执行。
-
发送的粘性事件默认会被缓存,并且相同类型的事件只会缓存当前最新的一个;
-
粘性事件与普通事件的差别:
6.1 普通事件: 发送普通事件的时候,只有已经注册成功的同事件类型的订阅者方才能够接收到该普通事件。事件发送后不会被缓存,在发送之后注册的同类型的订阅者方法无法接收到该事件;
6.2 粘性事件:发送粘性事件的时候,已经注册同事件类型的订阅者方法(sticky=true)能够接收到该通事件。并且框架对每一种事件类型都默认会缓存最新的一个粘性事件,也就是说在发送结束后再进行注册的同事件类型的粘性订阅者方法(sticky=true)会立马再次接受到该最新的粘性事件;
-
框架不会主动删除粘性事件,需要手动调用removeStickyEvent移除粘性事件,否则最后一个粘性事件会一直被缓存着,每次重新注册同事件类型的粘性订阅者方法时,都会再次执行该事件;
-
发送消息事件Class A后,接收该事件类型A的订阅方法、接收A的父类的订阅方法、接收A实现的接口的订阅方法等,都会触发执行;
-
子类会从父类继承订阅者方法;
-
子类与父类不能同时进行regisrer注册,否则会抛出异常,其实就是一个类中register不能连续调用2次;
源码分析
EventBus源码最关键的就是几个用来缓存的集合,搞懂其左右基本就明白了大体上的实现思路了: (源码阅读建议fork或者下载源码到android studio中查看,代码路径 github.com/yangjinze/E…记得切换到代码注释版本分支)
public class EventBus {
/**
* 缓存事件类型对应的继承体系和实现的接口列表,避免每次都重复解析获取
*
* key : 发送的事件对应的class,比如 post("123"), key则为String.class
* value : 事件class、事件实现的接口、事件的父类、父类实现的接口、父类的父类......这一连串有继承关系和接口实现关系的类集合
*
* 发送一个事件时,事件类型为其父类或者接口的订阅者方法也能被触发,比如:
*
* 假设A.class , B extends A , B implements C接口
* @Subscribe()
* public void subsA(A a) {}
* @Subscribe()
* public void subsC(C c) {}
* @Subscribe()
* public void subsB(B b) {}
*
* 则Post(B)的时候,上述3个订阅者方法都会被执行
*/
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
/**
* 存放订阅方法的接收的消息入参class --> 对应的订阅Subscription对象列表
*
*
* 作用:进行post(消息)的时候,根据 消息.class 就可以取出ubscription对象列表,然后逐一执行里面的订阅者方法
*/
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
/**
* 存放订阅者 -> 所拥有的订阅方法的入参class列表
*
* 订阅者: 调用register传入的对象, 比如 FirstActivity.this
* 订阅方法的入参class列表:
* 假设 FirstActivity 存在2个订阅者方法
* @Subscribe
* public void test(String msg)
* @Subscribe
* public void test(int type)
* 则对应列表[String.class, Integer.class]
*
* 作用: 下次根据unregister传入的对象,比如 FirstActivity.this就可以获取到列表 [String.class, Integer.class]
* 然后就可以从 subscriptionsByEventType 得到String.class 和 Integer.class对应的订阅方法对象列表
* 遍历订阅对象一致,则移除FirstActivity.this包含的所有订阅方法
*/
private final Map<Object, List<Class<?>>> typesBySubscriber;
/**
* 粘性事件缓存,比如postSticky("123")
* 则缓存String.class --> "123" ,可见对于每一个类型的事件只会缓存最新的粘性事件
*/
private final Map<Class<?>, Object> stickyEvents;
}
复制代码
注册相关 register与unregister
register
传入需要注册的对象,eventBus会去解析该对象中存在的订阅者方法,并与该对象建立联系关系:
//subscriber :订阅者,比如FirstActivity.this
public void register(Object subscriber) {
//获取到订阅者的类型,比如FirstActivity.class
Class<?> subscriberClass = subscriber.getClass();
//获取订阅者中符合条件的@Subscribe标注的订阅者方法列表
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
//这边遍历解析到的结果,根据优先级缓存在subscriptionsByEventType列表中,
//并且会判断是否是粘性订阅方法,是且存在符合的粘性事件时,则触发处理
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
复制代码
findSubscriberMethods
获取订阅者中符合条件的@Subscribe标注的订阅者方法列表:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//判断这个类相关订阅方法是否解析过了,解析过则从缓存中读取,
// 比如这样就避免了每次进入FirstActivity时执行register都需要重新再解析一遍
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//没缓存,重新解析,ignoreGeneratedIndex默认是false
//属性表示是否忽略注解器生成的MyEventBusIndex
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//解析得到订阅者方法列表
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
//调用register注册的订阅者,如果不存在符合条件的订阅者方法,则抛出异常
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
//缓存解析到的订阅者类对应的订阅者方法列表, 比如 FirstActivity - List<subscriberMethod>
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
复制代码
findUsingInfo
实际解析并得到订阅方法列表的执行步骤
//subscriberClass:订阅者对应的类,比如FirstActivity.class
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
//初始 findState.clazz = subscriberClass
while (findState.clazz != null) {
//获取订阅者的相关信息
findState.subscriberInfo = getSubscriberInfo(findState);
//一开始为null
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 {
//解析该subscriberClass,比如FirstActivity, 将其中的订阅者方法存放在列表
findUsingReflectionInSingleClass(findState);
}
//递归搜索父类中的订阅者方法,默认会进行父类搜索
//所以在父类中的订阅者方法也会一并被继承过来并且生效
findState.moveToSuperclass();
}
//返回解析到的订阅者方法列表,并释放资源
return getMethodsAndRelease(findState);
}
复制代码
findUsingReflectionInSingleClass
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
//获取订阅者类所有的方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
try {
methods = findState.clazz.getMethods();
} catch (LinkageError error) { // super class of NoClassDefFoundError to be a bit more broad...
String msg = "Could not inspect methods of " + findState.clazz.getName();
if (ignoreGeneratedIndex) {
msg += ". Please consider using EventBus annotation processor to avoid reflection.";
} else {
msg += ". Please make this class visible to EventBus annotation processor to avoid reflection.";
}
throw new EventBusException(msg, error);
}
findState.skipSuperClasses = true;
}
//遍历获取到的方法
for (Method method : methods) {
int modifiers = method.getModifiers();
//method必须是public,并且不能是static、abstract、桥接方法,订阅者方法的第一点限制
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//获取method入参列表对应的class数组,按顺序
Class<?>[] parameterTypes = method.getParameterTypes();
//这边限制了参数个数只能是1个,订阅者方法的第二点限制
if (parameterTypes.length == 1) {
//获取该方法上的@Subscribe注解,订阅者方法的第三点限制,必须要用@Subscribe注解声明
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//得到入参对应的class类,比如String.class
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
//获取注解中threadMode的值,用于指定订阅者方法运行在哪个线程
ThreadMode threadMode = subscribeAnnotation.threadMode();
//将订阅者方法存放在该list中; SubscriberMethod构造对应订阅者方法method,入参class,注解中的3个参数
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");
}
}
}
复制代码
subscribe
这边遍历解析到的结果,根据优先级缓存在subscriptionsByEventType列表中,并且会判断是否是粘性订阅方法,是且存在符合的粘性事件时,则触发处理
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType; //method,入参对应的class,比如String.class
//订阅对象, 存放订阅者对象与订阅方法对象 , FirstActivity.this 与 SubscriberMethod
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
/***
* CopyOnWriteArrayList是线程安全的List
*
* 获取入参类型对应的订阅列表,这样可以在进行post的时候,直接根据发送的消息参数.class
* 获取到需要执行的订阅者方法了吧,逐一进行调用
* ***/
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果这个订阅者方法已经添加过,重复添加则抛出异常;
//1.调用了2次register导致这种情况;
//2.父类调用了register,子类又调用了register,这样在子类中也会导致这种情况;
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//根据@Subscribe中参数priority指定的优先级存放找个订阅对象
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
//priority越大,优先级越高,放在越前面,更早被调用
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
//缓存这个订阅者对象,比如FirstActivity.this,所拥有的订阅方法入参class列表
//作用可以参考typesBySubscriber属性注释
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
//TODO ArrayList存在不妥的地方,应该用Set集合来避免添加了相同的Class
//不过一般一个订阅者也不会存在相同入参类型的订阅者方法
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
//处理粘性事件,有符合事件类型的,则执行
//注意的是这边粘性事件执行完,并不会从缓存中清除粘性事件,也就是下次再次注册或者有相关事件类型的定义方法注册时,都会再次执行这个粘性事件。
//粘性事件的删除需要主动删除,因为毕竟框架不清楚到底这个粘性事件有多少地方需要执行
if (subscriberMethod.sticky) {
if (eventInheritance) {//默认是true
// 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();
//eventType是candidateEventType的父类,或者2者同一类型时,返回true
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
复制代码
unregister
从typesBySubscriber获取该对象包含了几种入参类型不一样的订阅方法,比如有String.class和Man.class这2种。
然后从subscriptionsByEventType分别获取String.class和Man.class对应的所有订阅者方法列表,判断与之联系的订阅对象是否是subscriber,是则删除。
/**
* 取消注册,并且清除对应的订阅方法列表
* 避免一直缓存了该对象,导致内存泄漏
*
* @param subscriber
*/
public synchronized void unregister(Object subscriber) {
//获取该对象,比如FirstActivity.this所拥有的订阅方法消息入参class列表
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍历入参class列表
for (Class<?> eventType : subscribedTypes) {
//传入订阅者对象,与入参class
unsubscribeByEventType(subscriber, eventType);
}
//移除缓存的这个对象与列表
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
复制代码
unsubscribeByEventType
判断eventType对应的事件列表中的订阅者方法,如果与之联系的订阅者对象为subscriber,则移除该方法;
//subscriber调用unregister传入的对象,比如FirstActivity.this
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//获取入参class所对应的订阅方法对象列表
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);
//如果这个订阅者方法是该subscriber所有的,则进行移除
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
复制代码
消息发送:post或postSticky
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;
}
}
}
复制代码
postSingleEvent
/**
* 发送一个事件
*
* @param event 要发送的事件,EventBus.getDefault().post(event);
* @param postingState
* @throws Error
*/
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//event要发送的事件对象, 获取事件class类型,比如String.class
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//默认是true
if (eventInheritance) {
//递归获取事件class类型的相关父类,实现的接口,父类实现的接口
//也就是说相应入参为父类、实现的接口的订阅方法,都能被调用到
//调用顺序为 事件class > 接口 > 父类 > 父类接口 > 父类的父类 > 父类的父类接口.....
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));
}
}
}
复制代码
postSingleEventForEventType
/**
* 发送事件
*
* @param event 事件对象 ,比如post("123"),则为"123"
* @param postingState
* @param eventClass 事件类型, "123"对应String.class , 看调用的地方,也可能为其父类或者实现的接口
* @return
*/
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//获取该事件类型对应的订阅方法对象列表
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
//Subscription存放每个订阅者方法 与 订阅者对象
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted;
try {
//将事件传递给订阅方法@Subscribe
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;
}
复制代码
postToSubscription
根据指定的线程类型,开始调度执行
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
//根据@Subscribe里面threadMode所指定的线程做处理
switch (subscription.subscriberMethod.threadMode) {
case POSTING://默认的运行方式,运行在与发送方(post调用所在的线程)相同的线程,堵塞并直接执行
//堵塞并执行的意思是,post之后立马执行订阅者方法后,再接着执行post后面的代码
invokeSubscriber(subscription, event);
break;
case MAIN://运行在主线程
if (isMainThread) {//如果当前post发送方就是在主线程,堵塞并直接执行
invokeSubscriber(subscription, event);
} else {//如果当前post发送方不在主线程,最终由handler切换到主线程执行
mainThreadPoster.enqueue(subscription, event);
}
break;
case MAIN_ORDERED://运行在主线程
//与main的区别在于,MAIN_ORDERED都是排队执行,如果发送方当前是主线程的话,不会堵塞当前线程,
//而main则是如果当前是主线程会堵塞主线程直到订阅方法执行完毕
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) {//如果当前post发送方是主线程,进入后台线程排队
backgroundPoster.enqueue(subscription, event);
} else {//如果当前post发送方是后台线程,则直接堵塞该线程并执行
invokeSubscriber(subscription, event);
}
break;
case ASYNC://运行在异步线程,无论如何都另起线程来执行订阅方法,与post发送方所在线程不同
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
复制代码
postSticky
发送3个同事件类型class的粘性事件结束后,再进行粘性方法的注册,这时候只会接收到最后一个最新的粘性事件,而不是3个都能再次接收。
已经注册的同事件类型的方法无论是不是粘性方法都可以接收并执行。
private final Map<Class<?>, Object> stickyEvents = new ConcurrentHashMap<>();
public void postSticky(Object event) {
//缓存粘性事件,每种事件类型只会缓存最新的一个
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
//执行正常的事件发送,无论是不是粘性方法,已经注册的同事件类型的方法都可以接收并执行
post(event);
}
写在最后
我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在IT学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多程序员朋友无法获得正确的资料得到学习提升,故此将并将重要的Android进阶资料包括自定义view、性能优化、MVC与MVP与MVVM三大框架的区别、NDK技术、阿里面试题精编汇总、常见源码分析等学习资料免费分享出来。

知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。包含知识脉络 + 诸多细节,由于篇幅有限,下面只是以图片的形式给大家展示一部分。

【Android学习PDF+学习视频+面试文档+知识点笔记】
【Android高级架构视频学习资源】
Android部分精讲视频领取学习后更加是如虎添翼!进军BATJ大厂等(备战)!现在都说互联网寒冬,其实无非就是你上错了车,且穿的少(技能),要是你上对车,自身技术能力够强,公司换掉的代价大,怎么可能会被裁掉,都是淘汰末端的业务Curd而已!现如今市场上初级程序员泛滥,这套教程针对Android开发工程师1-6年的人员、正处于瓶颈期,想要年后突破自己涨薪的,进阶Android中高级、架构师对你更是如鱼得水,赶快领取吧!
【Android进阶学习视频】、【全套Android面试秘籍】可以简信我【学习】查看免费领取方式!
网友评论