网上已有很多对EventBus 的分析,自己再次记录更多的是自己的一种学习笔记,针对的更多是自己。通用性不大,参考意义一般。
从构造方法方法说起,构造方法可以用build 模式进行替换部分设置,其方式为
EventBus.builder()
.eventInheritance(false)
.build()
.register(this);
也可以设置为默认的方式 :
EventBus.getDefault().register(this);
要注意的是 register (Objecter) 这里不一定就要说注册 Activity 对象,可以接收其他的对象的。另外,我们看一下默认的参数他们拥有哪些参数,这些参数有哪些是比较重要的呢?
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
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;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
这里先不对这些属性进行分析,在后面用到的地方详细分析一下。
register 从注册说起
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
reigster 这个方法接收一个参数,这个参数就是订阅者,这里一般传当前类的对象,所以我们用 this 。 然后获取到当前类的class 对象,在通过 subscriberMethodFinder.findSubscriberMethods(subscriberClass); 找到当前订阅者的所有的方法,追进行看看这个方法的实现
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//METHOD_CACHE 缓存 先检查缓存是否包含相关list ,没有再去寻找订阅者方法的集合
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 这个ignoreGeneratedIndex 参数在构造方法里 默认为 false
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
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
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != 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);
}
findSubscriberMethods()流程很清晰,即先从缓存中查找,如果找到则直接返回,否则去做下一步的查找过程,然后缓存查找到的集合,根据上边的注释可知findUsingInfo()方法会被调用。继续看 findUsingInfo(),从
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
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();
}
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
上面的代码展示出 prepareFindState() 和 initForSubscriber () 就是初始化了 SubscriberMethodFinder 内部类的 FindState ,把FindState 内部的class 赋值为订阅者,FindState 类是辅助类,帮助查找订阅者相关的方法。接着是 判断 FindState. clazz 是否为空,刚刚说了 prepareFindState()和initForSubscriber ()就是给 FindState. clazz 赋值,所以这里不为空,继续往下走,接着是
// 查找 订阅者的相关信息
findState.subscriberInfo = getSubscriberInfo(findState);
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
假如这个订阅者第一次订阅相关事件,那么在getSubscriberInfo 方法里面,这些属性的判空,肯定都会为空的,所以第一次订阅这些 得到的 findState.subscriberInfo 对象为空,就会到 findUsingReflectionInSingleClass 方法,这个方法通过java反射的相关方法获取到订阅者所有的方法,并挑选出符合条件的方法:
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 (Method method : methods) {
// 获得方法的修饰符
int modifiers = method.getModifiers();
// 如果是public类型,但非abstract、static等
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 获得当前方法所有参数的类型
Class<?>[] parameterTypes = method.getParameterTypes();
// 如果当前方法只有一个参数
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
// 如果当前方法使用了Subscribe注解
if (subscribeAnnotation != null) {
// 得到该参数的类型
Class<?> eventType = parameterTypes[0];
// checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true
if (findState.checkAdd(method, eventType)) {
// 得到Subscribe注解的threadMode属性值,即线程模式
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 创建一个SubscriberMethod对象,并添加到subscriberMethods集合
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");
}
}
}
看到代码我们知道符合条件的方法的条件就是:
注解信息,参数信息,满足一定条件。我们的订阅方法必须有且只有一个参数,否则会抛出异常的,订阅方法必须是public修饰的,而且不是静态、不是抽象方法,否者也会抛出异常;必须包含注解 Subscrbe ;
到此register()方法中findSubscriberMethods()流程就分析完了,我们已经找到了当前注册类及其父类中订阅事件的方法的集合。
接下来,我们分析下具体的注册流程,即register()中的subscribe()方法。首先,我们看一下subscribe()方法的源码:
// Must be called in synchronized block
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);
}
}
}
其实 subscribe 这个方法的本质就是 根据事件名(就是register(this) 这个this代表的类名)为key ,把这个类的所有事件list 作为value ,形成一个map 集合。得到了subscriptionsByEventType、typesBySubscriber两个 HashMap。typesBySubscriber 的key/value 为 当前类的class 及装有类名的list ;subscriptionsByEventType 的key/value 为 当前类的class 及符合条件的方法;
取消注册unRegister
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
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--;
}
}
}
}
/** 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 {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
取消的本质就是把上面两个Map 清空而已。没有什么。
post 事件/处理事件
事件的发送其实比较简单,只要我们一直往下追代码就可以了,现在列出方法调用路径和简单说明
postSingleEvent(发送一个事件) 、postSingleEventForEventType(根据之前的map寻找事件发送) 、postToSubscription(发送给订阅者) 、 invokeSubscriber (处理事件)
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;
}
}
}
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));
}
}
}
postSingleEventForEventType(根据之前的map寻找事件发送)
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));
}
}
}
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 把该事件入队在发送(下面的可以和这里的逻辑进行对比)
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 (处理事件)
void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
就是通过反射进行事件处理,所以eventBus 本质核心也是在A地方想要执行B地方的代码,通过定义了一些特殊的标识(事件)来连接A、B,然后通过反射去达到目的,其他所有的功能都是在这个基础上去拓展的。
再来分析一下,如何实现跨线程?很简单,android 的跨线程本质就只有handler ,肯定就是handler 或者是 handler的一些包装类。这里就是搞了一个队列结合了handler 。
sticky事件
public void postSticky(Object event) {
//提供一个map记录一下粘性事件类名及名称
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
//事件注册逻辑中事件订阅
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
......
// 处理粘性事件
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 {
//从之前的粘性缓存map中取出事件,并发送事件去处理
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
//事件处理
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
//回到了普通事件的处理
postToSubscription(newSubscription, stickyEvent, isMainThread());
}
}
从上面的代码来看,粘性事件的发送、处理逻辑 为:发送的粘性事件先储存起来,然后再注册的时候检测合法的方法时,判断该方法是否能够处理粘性事件,能够处理则从之前的map中取出事件,并发送处理。这样就实现了事件的先发送后订阅处理。
分析完后,问自己几个问题或者作为面试题目?
- eventBus 如何实现线程的切换?
- eventBus 如何实现粘性事件的先发送后处理事件?
- eventBus 如何通过配置提升效率?
1. 线程切换 通过handler 及内部的队列实现的
2. 先把粘性事件存储起来,然后再注册的时候检测事件是否合格且支持粘性及事件的标识 ,通过后就立即处理事件
3. eventbus 事件支持继承,用属性eventInhertiance 表示,我们可以关闭该属性,这样会加快速度。