EventBus源码解析(史上最全的源码解析)
Eventbus实现的两种方式
第一种:初始化配置获取eventbus对象,使用建造者设计模式
EventBus eventBus=EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).build();
1.点击builder()进入源码
public static EventBusBuilder builder() {
return new EventBusBuilder();
}
源码中是创建一个EventBusBuilder对象。
2.得到eventbusbuilder对象进行来进行设置一些配置
throwSubscriberException
是否抛出异常,可以设置在debug模式下进行来抛出日志
3.点击build()方法进行源码
public EventBus build() {
return new EventBus(this);
}
在这里返回的是创建的eventbus的对象,点击new EventBus(this)的eventbus进入下一层源码
EventBus(EventBusBuilder builder) {
//事件订阅类型集合
subscriptionsByEventType = new HashMap<>();
//订阅者类型的集合
typesBySubscriber = new HashMap<>();
//联系集合
stickyEvents = new ConcurrentHashMap<>();
//主线程初始化操作
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
//子线程初始化操作
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;
}
第二种:获取eventbus对象
使用方法:EventBus.getDefault();
点击getDefault()方法进入源码,源码如下:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
通过单例设计模式得到eventbus对象,点击eventbus()构造方法跳到如下源码:
public EventBus() {
this(DEFAULT_BUILDER);
}
(1)DEFAULT_BUILDER这个的代码
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
结果发现是创建eventbusbuilder对象
(2)点击this进入到EventBus(EventBusBuilder builder) {}这个方法里面就是上面的那个方法
得到eventbus对象后进行开始注册
使用方式: eventBus.register(this);
点击进入源码:
public void register(Object subscriber) {
//获取类 获取出来的结果 例如:com.xgkj.eventbusdemo.MainActivity
Class<?> subscriberClass = subscriber.getClass();
////主要查找又什么方法是在这个函数里面
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
//进行同步操作
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
一、SubscriberMethod类里面的源码进行解析
public class SubscriberMethod {
final Method method;//方法
final ThreadMode threadMode;//执行线程
final Class<?> eventType;//接收的事件类型
final int priority;//优先级
final boolean sticky;
/** Used for efficient comparison */
String methodString;
....
}
二、这个方法 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
里面源码进行分析:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
2
3 //首先从缓存中读取
4 List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
5 if (subscriberMethods != null) {
6 return subscriberMethods;
7 }
8
9
10 //是否忽略注解器生成的MyEventBusIndex类
11
12 if (ignoreGeneratedIndex) {
13 //利用反射来获取订阅类中的订阅方法信息
14 subscriberMethods = findUsingReflection(subscriberClass);
15 } else {
16 //从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
17 subscriberMethods = findUsingInfo(subscriberClass);
18 }
19 if (subscriberMethods.isEmpty()) {
20 throw new EventBusException("Subscriber " + subscriberClass
21 + " and its super classes have no public methods with the @Subscribe annotation");
22 } else {
23 //保存进缓存
24 METHOD_CACHE.put(subscriberClass, subscriberMethods);
25 return subscriberMethods;
26 }
27 }
源码分析:
1.List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
METHOD_CACHE(方法缓存集合)这个用来干什么的呢?我们来看一下这个METHOD_CACHE实现代码:
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
是创建了一个集合的代码,键是类,值是一个集合里面存放的是订阅方法
- 继续往下分析
判断subscriberMethods这个对象是否为空,为空的继续往下执行,不为空的话返回这个集合
3.ignoreGeneratedIndex(没有生成的索引布尔值)进行分析,我们来看一下这个参数的代码:
private final boolean ignoreGeneratedIndex; 默认值false
如果是true执行findUsingReflecti(subscriberClass);
,否则 findUsingInfo(subscriberClass);
(1)先看一下findUsingReflection(subscriberClass);
里面的源码
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
这段代码进行分析,FindState
其实就是一个里面保存了订阅者和订阅方法信息的一个实体类,包括订阅类中所有订阅的事件类型和所有的订阅方法等。
我们看到会首先创建一个FindState对象并执行findUsingReflectionInSingleClass(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;
}
//遍历所有方法,忽略private类型的,最后如果是公有,并且不是
//java编译器 生成的方法名,那么就是我们要的了。
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) {
//得到注解
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");
}
}
}
可以看到,首先会得到订阅类的class对象并通过反射获取订阅类中的所有方法信息,然后通过筛选获取到订阅方法集合。
程序执行到此我们就获取到了订阅类中的所有的订阅方法信息,接下来我们就要对订阅方法进行注册;
subscribe(subscriber, subscriberMethod);
//参数:1订阅者2订阅方法集
// 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);
//将订阅者添加到subscriptionsByEventType集合中
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);
}
//将该事件类型添加到typesBySubscriber中
subscribedEvents.add(eventType);
//如果接收sticky事件,立即分发sticky事件
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);
}
}
}
上面用到的类进行分析
(1)Subscription类分析
//订阅者信息
final class Subscription {
final Object subscriber;//订阅者
final SubscriberMethod subscriberMethod;//订阅方法
}
(2)subscriptionsByEventType
key订阅方法类型 values 所有订阅了该类型的订阅者集合
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
(3)typesBySubscriber
key订阅者 values订阅事件集合
Map<Object, List<Class<?>>> typesBySubscriber;
了解了这几个对象,上面的代码就很容易看懂了,
1、首先获取订阅方法的参数类型即订阅事件类型
2、根据订阅事件类型获取该事件类型的所有订阅者
3、将该订阅者添加到该事件类型的订阅者集合中即:subscriptionsByEventType
4、获取订阅者所有的订阅事件类型
5、将该事件类型添加到该订阅者的订阅事件类型集中即:typesBySubscriber
2.findUsingInfo(subscriberClass);
这个方法下面的源码进行分析
/**
* 查找用户信息
* @param subscriberClass
* @return
*/
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//FindState其实就是一个里面保存了订阅者和订阅方法信息的一个实体类,包括订阅类中所有订阅的事件类型和所有的订阅方法等。
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);
}
(1)getSubscriberInfo(findState);
这个方法的源码解析
private SubscriberInfo getSubscriberInfo(FindState findState) {
//1.订阅信息不能为空 2.获取的订阅信息不能为空
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;
}
(2)getMethodsAndRelease(findState)
这个方法就是获取方法并进行释放
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.recycle();这个方法进行解析
查看到方法源码,其实就是做了释放的操作
void recycle() {
subscriberMethods.clear();
anyMethodByEventType.clear();
subscriberClassByMethodKey.clear();
methodKeyBuilder.setLength(0);
subscriberClass = null;
clazz = null;
skipSuperClasses = false;
subscriberInfo = null;
}
二、事件分发解析
接下来我们来分析EventBus的事件分发机制即:EventBus.getDefault().post(“Test”);
我们从post方法入手
/** Posts the given event to the event bus. */
public void post(Object event) {
//获取当前线程的postingState
PostingThreadState postingState = currentPostingThreadState.get();
//取得当前线程的事件队列
List<Object> eventQueue = postingState.eventQueue;
//将该事件添加到当前的事件队列中等待分发
eventQueue.add(event);
if (!postingState.isPosting) {
//判断是否是在主线程post
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?
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();//当前线程的事件队列
boolean isPosting;//是否有事件正在分发
boolean isMainThread;//post的线程是否是主线程
Subscription subscription;//订阅者
Object event;//订阅事件
boolean canceled;//是否取消
}
PostingThreadState中包含了当前线程的事件队列,就是当前线程所有分发的事件都保存在eventQueue事件队列中
以及订阅者订阅事件等信息,有了这些信息我们就可以从事件队列中取出事件分发给对应的订阅者。
PostingThreadState怎么获得?
ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,而这段数据是不会与其他线程共享的。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
可以看出currentPostingThreadState的实现是一个包含了PostingThreadState的ThreadLocal对象,这样可以保证取到的都是
自己线程对应的数据。
我们有了PostingThreadState获取到了当前线程的事件队列,接下来就是事件分发,我们来看
postSingleEvent(eventQueue.remove(0), postingState);
事件分发
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//得到事件类型
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//是否触发订阅了该事件(eventClass)的父类,以及接口的类的响应方法.
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://默认的 ThreadMode,表示在执行 Post 操作的线程直接调用订阅者的事件响应方法,
//不论该线程是否为主线程(UI 线程)。
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);
}
}
以上的四种threadMode可以看代码注释简单了解一下,通过一下代码我们来看一下订阅方法最后是通过invokeSubscriber(subscription, event);来执行的
//最终通过反射调用订阅者的订阅函数 并把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、首先获取当前线程的PostingThreadState对象从而获取到当前线程的事件队列
2、通过事件类型获取到所有订阅者集合
3、通过反射执行订阅者中的订阅方法
是不是很简单。
我们来看一下整个事件分发的流程图
三、取消注册的解析
我们简单看一下取消注册的源码EventBus.getDefault().unregister(this);
/** 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 {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
再来看一下: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--;
}
}
}
}
总结一下:
1、首先获取订阅者的所有订阅事件
2、遍历订阅事件
3、根据订阅事件获取所有的订阅了该事件的订阅者集合
4、将该订阅者移除
5、将步骤1中的集合中的订阅者移除
这样就完成了取消订阅的全过程;
最后我们从开发者的角度来总结一下EventBus的工作原理
订阅逻辑
1、首先用register()方法注册一个订阅者
2、获取该订阅者的所有订阅的方法
3、根据该订阅者的所有订阅的事件类型,将订阅者存入到每个以 事件类型为key 以所有订阅者为values的map集合中
4、然后将订阅事件添加到以订阅者为key 以订阅者所有订阅事件为values的map集合中
4.1、如果是订阅了粘滞事件的订阅者,从粘滞事件缓存区获取之前发送过的粘滞事件,响应这些粘滞事件。
事件发送逻辑
1、首先获取当前线程的事件队列
2、将要发送的事件添加到事件队列中
3、根据发送事件类型获取所有的订阅者
4、根据响应方法的执行模式,在相应线程通过反射执行订阅者的订阅方法
取消逻辑
1、首先通过unregister方法拿到要取消的订阅者
2、得到该订阅者的所有订阅事件类型
3、遍历事件类型,根据每个事件类型获取到所有的订阅者集合,并从集合中删除该订阅者
4、将订阅者从步骤2的集合中移除
推荐阅读
-
spring5 源码深度解析----- 被面试官给虐懵了,竟然是因为我不懂@Configuration配置类及@Bean的原理
-
AngularJS动态生成div的ID源码解析
-
ArrayList构造方法的源码解析
-
基于Spring注解的上下文初始化过程源码解析(一)
-
axios 源码解析(下) 拦截器的详解
-
SpringBoot 源码解析 (七)----- Spring Boot的核心能力 - SpringBoot如何实现SpringMvc的?
-
SpringBoot 源码解析 (六)----- Spring Boot的核心能力 - 内置Servlet容器源码分析(Tomcat)
-
Laravel源码解析之路由的使用和示例详解
-
Vue源码解析之Template转化为AST的实现方法
-
解析xHTML源码的DLL组件AngleSharp介绍