介绍
EventBus是Android中比较流行的事件总线框架,可以无耦合的在各个组件之间传递事件,本篇文章就来介绍一下它的用法与部分重要源码。
使用方式
使用EventBus需要关注几个步骤:
- 注册监听类
- 定义事件类
- 实现事件回调方法
- 发送事件
注册监听类
在组件里调用register方法,可以让EventBus注册此类中定义的订阅方法。
EventBus.getDefault().register(this);
定义事件类
定义自己的事件类,没有什么特殊规定。
public abstract class BaseEvent {
protected String eventType;
public String getEventType() {
return eventType;
}
}
实现事件回调方法
EventBus3.0之后,对于事件回调方法的名称没有要求,只需要加上@Subscribe注解就可以了,还可以指定函数执行所在的线程。
//这里定义了线程模式MAIN,使得事件在UI线程进行回调
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(OrderEvent event) {
switch (event.getEventType()) {
case EventConstans.ORDER_EVENT_NORMAL:
Toast.makeText(this, "啊啊啊", Toast.LENGTH_SHORT).show();
break;
}
}
发送事件
发送也是很简单,只需要调用postEvent,传入我们自定义的事件类型就好了。
EventBus.getDefault().post(new OrderEvent(EventConstans.ORDER_EVENT_NORMAL));
ThreadMode
在定义回调函数的时候用到了threadMode,这里还需要了解一下它们的类型:
- POSTING:回调直接在事件发布者发布的线程执行,不切换线程。(默认)
- MAIN:保证回调在UI线程执行。
- BACKGROUND:如果在主线程中发布,回调会在一个新的线程中执行;如果不在主线程中发布,则会直接在当前线程中执行。
- ASYNC:无论在哪个线程中发布,都会在一个新线程中执行。
粘性事件
EventBus还有一种粘性事件,可以在订阅者订阅时收到发布者之前发布的事件,它的发布和接收需要这样写:
//发送:使用postSticky
EventBus.getDefault().postSticky(new OrderEvent(EventConstans.ORDER_EVENT_NORMAL));
//接收:@Subscribe(sticky = true)
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onEvent(OrderEvent event) {
switch (event.getEventType()) {
case EventConstans.ORDER_EVENT_NORMAL:
Toast.makeText(this, "啊啊啊", Toast.LENGTH_SHORT).show();
break;
}
}
EventBus用起来是很简单的,我们要理解它还是得看看源码。
源码解析
获取EventBus
//获取EventBus的单例对象,双重检查锁
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
注册订阅者类
public void register(Object subscriber) {
//获得对象的类
Class<?> subscriberClass = subscriber.getClass();
//寻找这个类的EventBus订阅方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
//遍历订阅方法,对每个方法订阅一次
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
1. 获得传入对象的类对象。
2. 获得这个类中定义的订阅函数。
3. 对每个订阅函数进行订阅操作。
我们进入步骤2中看下是怎么根据类取得订阅函数的。
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//从缓存中取出订阅函数集合
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
//缓存中有就返回了
if (subscriberMethods != null) {
return subscriberMethods;
}
//这个字段跟EventBus查找时的索引有关,定义了可以提升查找效率,默认为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.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
1. 从缓存中取出订阅方法集合。
2. 如果缓存中没有,选择合适的方法寻找订阅方法。
3. 如果没有找到订阅方法,抛出异常程序崩溃。
4. 如果找到了订阅方法,将它和订阅者类对象组成键值对存储到缓存。
我们继续跳到查找订阅方法的findUsingInfo里面看下。
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);
}
1. 从状态池获得一个状态对象。
2. 将订阅者类传入,设置一些状态对象的参数。
3. 通过状态对象寻找订阅者信息,如果找到就获取到了订阅方法集合。
4. 将方法集合存入当前状态对象。
5. 3中没有找到订阅者信息,则调用方法,用反射去寻找订阅方法。
6. 状态对象指向父类,再次循环,找父类中的订阅方法。
我们看下没有找到订阅者信息情况下,利用反射寻找订阅方法的过程。
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
//获取本类以及父类或接口中所有public方法,写在这的具体原因看issues
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
//遍历方法集合,结合注解中的一些参数等
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");
}
}
}
1. 获取订阅类中定义的方法。
2. 遍历方法集合,检测完合法性,将合法的订阅方法封装,存入状态对象
接下来就是一步步返回了,至此我们已经获取到所有的订阅方法,接下来看订阅方法的订阅过程。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//获得事件类型
Class<?> eventType = subscriberMethod.eventType;
//封装订阅者与订阅方法为一个订阅对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//通过事件类型找到订阅对象集合
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//没找到,新建订阅对象集合,put进map
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);
}
//put当前事件类型进去
subscribedEvents.add(eventType);
//粘性事件处理,如果之前有粘性事件,则取出并发送给订阅者
if (subscriberMethod.sticky) {
//eventInheritance参数默认为true,会对事件类型的父类也进行查找
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. 根据订阅方法获取事件类型。
2. 将订阅者和订阅方法组合成一个订阅对象。
3. 将订阅对象排序后,存入一个Map<事件类型,订阅对象集合>当中。
4. 根据订阅者获取到它可以相应的事件类型集合,存入此事件类型。
5. 处理粘性事件。
至此事件的注册过程就分析完了。
事件的发送过程
事件的发送过程是第二个重点,它的起点是post方法:
public void post(Object event) {
//保存事件队列和线程的状态信息,是一个ThreadLocal对象
PostingThreadState postingState = currentPostingThreadState.get();
//获得事件队列
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
//如果当前事件不在分发中,进行分发逻辑
if (!postingState.isPosting) {
//通过Looper判断当前是否为主线程
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;
}
}
}
1. 获得post线程状态对象。
2. 从这个线程状态对象中取得事件队列。
3. 如果事件没有在分发中,进行分发,同时识别当前执行的线程。
4. 循环取出事件队列中的事件进行分发过程。
可以看到具体的分发流程在postSingleEvent中:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//获得事件类型对象的类
Class<?> eventClass = event.getClass();
//是否找到订阅的类
boolean subscriptionFound = false;
//是否查找父类的标志,默认true
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));
}
}
}
1. 找到我们自定义事件类型的类对象。
2. eventInheritance若为true,会找到这个事件类型的自身和父类,逐一进行事件分发。
3. eventInheritance为true,只对自身事件类型进行分发。
可以看到无论是自身还是父类,都实际调用了postSingleEventForEventType方法进行下一步操作。
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;
}
1. 根据事件类型获得订阅对象集合。
2. 通过postToSubscription向订阅者进行事件分发。
接下来调用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.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找到合适的线程来调用订阅函数而已。
取消注册
取消就很简单了,大致就是在map里把相关的对象remove就好了,入口为unregister方法,我们来看下:
public synchronized void unregister(Object subscriber) {
//根据订阅者找到订阅的事件类型集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍历事件类型集合,调用unsubscribeByEventType实际解除关联
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//在Map<订阅者,事件类型集合>中删除这个订阅者对应的entry
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
看下unsubscribeByEventType方法的内容:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根据事件类型获得订阅对象集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
//遍历订阅对象集合,如果订阅对象内的订阅者是需要unregister的,从订阅对象集合中进行移除
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--;
}
}
}
}
这一步就是在订阅对象集合中找到这个订阅者,删除所有相关订阅对象的过程。
结尾
至此EventBus主要的功能就分析完了,如果有不对的地方欢迎大家指正哈。