csdn博客:http://blog.csdn.net/hjjdehao
在看源码之前,需要掌握的主要知识点:集合、反射、注解。
框架基本上是用这三方面的知识点写的,没掌握的最好去掌握下,不然看的时候会晕头转向。
一、注册源码解析
注册的一系列流程,其流程图(来自网络)如下:
这里写图片描述 我们在使用EventBus的时候,首先做的第一件事就是给事件注册对象了,通俗来讲就是说要接收消息,需要登记信息,方便有消息可以通知到你。
那么EventBus是如何注册信息的呢?又是如何接收事件?
我们带着疑问看代码,效果会更好。
注册订阅者代码:
//将当前对象进行注册,表示这个对象要接收事件
EventBus.getDefault().register(this);
注册源码:
public void register(Object subscriber) {
//获取订阅者的Class类型
Class<?> subscriberClass = subscriber.getClass();
//根据订阅者的Class类型,获取订阅者的订阅方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List< SubscriberMethod > subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
这句代码表示的是:通过订阅者的Class类型获取订阅者的所有的订阅方法。那它是如何获取所有的订阅方法的呢?
我们再看一下findSubscriberMethods方法的源码
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//先从缓存中查找是否存在订阅方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略注解器生成的MyEventBusIndex类
if (ignoreGeneratedIndex) {
//利用反射来获取订阅类中的订阅方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
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.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
上面的源码在查找订阅方法信息是用了两种方式,如下所示:
if (ignoreGeneratedIndex) {
//利用反射来获取订阅类中的订阅方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
subscriberMethods = findUsingInfo(subscriberClass);
}
ignoreGeneratedIndex的判断是看你的build配置文件是否配置相关注解处理器信息如下:
这里写图片描述
要说两种方式区别无非就是性能和速度,相对说注解处理比反射来的好,看下面的图就清楚了。
这个方法的大致逻辑是这样:
先从缓存中查找订阅方法信息,如果没有就利用反射或注解来获取订阅方法信息。
1、使用注解处理器
findUsingInfo(Class< ? > subscriberClass)
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);
}
EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,
处理其中所包含的信息,然后生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的
信息速度要快。
EventBus 3.0使用的是编译时注解,而不是运行时注解。通过索引的方式去生成回调方法表,通过表可以看出,极大的提高了性能。
注册订阅者是为了后面的事件分发,以便知道该将事件发送给谁,而事件的接收就是订阅者的订阅方法。
事件分发代码:
EventBus.getDefault().post(new Event());
看post方法的源码:
参数即要发送的事件对象
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;
}
}
}
PostingThreadState 是EventBust的静态内部类,它保存当前线程的事件队列和线程状态。
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();//当前线程的事件队列
boolean isPosting;//是否有事件正在分发
boolean isMainThread;//post的线程是否是主线程
Subscription subscription;//订阅者
Object event;//订阅事件
boolean canceled;//是否取消
}
参数一:事件对象
参数二:发送状态
postSingleEvent(eventQueue.remove(0), postingState)执行源码
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//获取事件对象的Class类型
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) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
postSingleEventForEventType(event, postingState, eventClass)
看了那么多的源码才发现这个方法才是罪魁祸首。最终发射事件的方法。
那好接着看看他的源码:
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;
}
postToSubscription(subscription, event, postingState.isMainThread);
开始处理订阅者的信息
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);
}
}
invokeSubscriber(subscription, event)
参数一:订阅者
参数二:事件对象
最后是通过反射调用实现的。
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);
}
}
事件分发逻辑:
1. 获取事件队列。
2. 循环取出队列中的事件。
3. 获取订阅者集合,然后遍历,最后通过反射调用订阅者的订阅方法。
三、取消注册解析
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 {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
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--;
}
}
}
}
取消注册逻辑:
1、首先根据订阅者获取所有订阅事件。
2、遍历订阅事件集合。
3、根据订阅事件获取订阅该事件的订阅者集合。
4、遍历订阅者集合,然后根据传入的订阅者做比较,判断是否是同一订阅者。如果是则移除,反之。
参考:http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html
网友评论