EventBus3.1源码解读,深入的学习
关于EventBus
首先放上EventBus的github地址https://github.com/greenrobot/EventBus;
具体的使用方法这里不在详细介绍了,度娘会告诉你,也比较简单,今天主要学习一下关于这个框架的源码,关于EventBus的源码网上也比较多,但是别人的终归是别人的,看很多遍不如自己学一次记得牢,所以就一起走一遍吧,
看看register做了什么
从使用这个方法的第一个地方入手
EventBus.getDefault().register(this);
看看这个getDefault()方法;
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
这个就是一个单例,获取一个EventBus对象实例,这个应该都可以看懂;
再看看register()做了什么呢?
public void register(Object subscriber) {
//获取到我们 传入的类 的class对象,也就是订阅者
Class<?> subscriberClass = subscriber.getClass();
//获取所以订阅者里面的订阅方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
这个subcriber就是我们在Activity或者Fragment中初始化的时候传递的this,也就是需要需要注册Eventbus事件的类,通过getClass();这里有一个subscriberMethodFinder,看看这个家伙是什么呢?
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();//一个日志类
//Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; subcription是订阅者和订阅方法的一个类 key为订阅者,value为订阅者和一个方法的实例的集合
subscriptionsByEventType = new HashMap<>();
//所以订阅方法的参数类型的一个map,key是我们的每一个订阅者的class类,value是该订阅者中所有订阅方法的一个list
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;
//在这里被初始化了,其他通过这个名字也可以猜出来了,查找类里面的Subscriber方法的一个类
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;
}
这里有一个类有必要看一下
/** Used internally by EventBus and generated subscriber indexes. */
public class SubscriberMethod {
final Method method; //Java通过反射获取到的订阅类的信息
final ThreadMode threadMode; //订阅类中订阅方法的线程模型
final Class<?> eventType; //订阅方法参数的Class对象,也就是我们的Model的Class对象
final int priority; //订阅回调方法的优先级
final boolean sticky; //订阅回调方法是否是粘性的
/** Used for efficient comparison */
String methodString; //订阅方法的方法名
通过代码可以看出 SubscriberMethod 其实就是一个Model类,它代表了:某一个订阅类的订阅方法信息。
接着看findSubscriberMethods方法(如果不关心如何find这些方法的可以略过继续往下看)
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略索引我们EventBus的index
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.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
这里首先去METHOD_CACHE这个map中去找是不是已经有这个集合如果有直接返回,如果没有,通过两个方法findUsingReflection(subscriberClass);和 findUsingInfo(subscriberClass)去查找出这个类中所以得订阅方法,然后存入METHOD_CACHE中并return;那我们就接着给这个方法里面看
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
//一个Model类,记录查找状态的,
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
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) {
//判断是不是public方法的
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {//参数只能有一个
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
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");
}
}
}
这里可以看出订阅者方法有几个注意事项:
1.必须是public,不能是abstract;
2.必须有@Subcribe注解;
3.方法必须有且只有一个参数
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);
}
代码特别多我们只看重点,两个方法中其实只是多了一个内部类FindState 记录find状态,主要方法在 findUsingReflectionInSingleClass(findState);
了解了一下关于我们添加的注册方法和类如何被找到的,继续回到register方法看
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
拿到这些方法后一个遍历,那我们就看看这个subscribe这个方法
// Must be called in synchronized block
//subscriber订阅者就是我们register时候传入的对象,也就是我们的订阅者
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
//创建Subscription,参数为:订阅者(subscriber)和订阅方法的信息类(subscriberMethod)
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//这个异常是不是很常见?是不是发生在我们重复注册的时候?!
//原因:该参数Class对象对应的集合重复添加了该对象,所以报错
//如果我们重复注册了,那么之前已经执行过了,subscriptions.add(i, newSubscription);
//此时subscriptions 已经包含了该对象,所以报错
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);
//判断是不是粘性事件,如果是粘性事件判断粘性事件的Map中是否有该参数的订阅方法,会被直接执行
if (subscriberMethod.sticky) {
//是不是考虑事件的super类,这里跟post方法里是一样的,这里如果看不明白先往后看后面有同样的代码
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);
}
}
}
将所以得订阅者和订阅方法放在了subscriptionsByEventType这个map中,
所以得订阅方法的参数的type放在了typesBySubscriber中
最后是对于粘性事件的一个处理
到这里register就基本完成了,放一个流程图吧
Post方法的深入
register和我们@Subscribe订阅方法看过了,我们接下来看看入和将事件发送过去的呢?
首先我们进去看看post的源码
/** Posts the given event to the event bus. */
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;
}
}
}
这里有一个PostingThreadState postingState,那我就跟过去看看这是什么呢?
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>();//事件队列
boolean isPosting;//是否正在执行
boolean isMainThread;//是否是主线程
Subscription subscription;//事件信息
Object event;//事件
boolean canceled;//是否被cancle
}
currentPostingThreadState 是一个ThreadLoacl,是Eventbus的一个成员变量,
很简单吧,继续往下看 postSingleEvent(eventQueue.remove(0), postingState);
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//我们post的bean的类型。
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//事件的super类或者是接口的类型是否可以接受(多态的考虑)
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这个是build中的一个boolear值,意义是如果我们post定义的是一个子类,但是subscribe方法是他的父类,也会收到,如果是false就收不到了。
接着往下面看,有一个postSingleEventForEventType(),进去看看
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//从map中根据事件类型获取到所以得订阅方法的一个集合
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;
}
这里可以看见subscriptionsByEventType通过这个map,拿到所以是跟个参数类型的订阅方法的一个集合,拿到相关参数调用了 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 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);
}
}
哎呀终于绕过来了,看的处理了吧,这里是跟我们每个订阅方法的threadMode的类型判断需要在哪里执行然后通过反射调用了我们的订阅方法;
这里post就看完了,也放一个流程图吧
这里在看一下粘性事件(postSticky)的发送吧:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
哈哈,是不是超级简单啊,只是多了一步把这个事件放在一个粘性事件的集合中,当其他订阅者被register或先获取一下这个集合里面的方法执行一下
那我们就具体看看每一个方法吧:
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 的 unregister
/** 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());
}
}
这里先是从typesBySubscriber获取到这个类中所以得订阅者的方法,根据订阅方法里面的参数和订阅方法找到所以的订阅事件并移除unsubscribeByEventType(subscriber, eventType);
/** 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--;
}
}
}
}
这里比较简单了就,放一个图吧
总结
我们register时候会将我们的@subscriber方法的跟所在的类存入达到一个Map(subscriptionsByEventType)中,
key为方法的参数的class类型,value为一个List集合放着我们所以该参数的方法,
还有一个Map(typesBySubscriber),Key为订阅者的对象,value是所以订阅方法的参数的class。
当我们调用post方法的时候,在根据post的参数获取我们的type类型,根据然后在这个map中找出所以这个参数的方法的集合,最后通过反射调用。
尾声
这里是一个菜鸟的学习历程,如果有问题可以评论,会及时纠正,如果又不懂的也可以评论,我会第一时间回复,学习路漫漫,为自己加油。
参考和借图