EventBus的使用,以及源码分析
EventBus的使用
EventBus能够简化各组件间的通信,能够有效的分离事件的发送方和接收方,能避免复杂和容易出错的依赖性和生命周期的问题。
EventBus的三要素
- Event事件,可以是任意类型。
- Subscriber事件订阅者,需要进行注册。
- Publisher事件的发布者。
EventBus的用法
添加依赖
implementation 'org.greenrobot:eventbus:3.1.1'
注册事件
override fun onStart() {
EventBus.getDefault().register(this)
super.onStart()
}
当我们需要在Activity或Fragment里订阅事件的时候,我们需要注册EventBus。我们一般选择在onStart()里去注册。onStop()里去解除。
解除事件
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
解除事件一定需要,为了防止内存泄漏。
发送事件
EventBus.getDefault().post("发送EventBus事件,任何类型都可以。")
处理事件
@Subscribe(threadMode = ThreadMode.MAIN)
fun MessageEventPost(message: String) {
//todo
}
EventBus注解参数
注解代码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.POSTING;
boolean sticky() default false;
int priority() default 0;
}
threadMode():运行在那个线程,枚举类型。(POSTING,MAIN,MAIN_ORDERED,BACKGROUND,ASYNC)
sticky():是否是粘性事件。
所谓粘性事件,就是在发送事件之后再订阅该事件也能收到该事件。
priority():优先级(0-100)
EventBus源码分析
EventBus注册代码
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
//通过subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod里包含了这个方法的 Method 对象,
//以及将来响应订阅是在哪个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优先级 priority ,
//以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的所有 Subscriber 注解方法属性。
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//先在缓存中读取
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGeneratedIndex 默认值为false,findUsingInfo(Class<?> subscriberClass)
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 {
//订阅者Class存入缓存
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//获取FindState()
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//findState.subscriberInf == null is true
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);
}
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// 通过发射获取订阅类的所有方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
//获取类的修饰符
int modifiers = method.getModifiers();
//找到所有声明为public的方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//获取参数的class
Class<?>[] parameterTypes = method.getParameterTypes();
//只可以包含一个参数
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//获取事件的Class,也就是方法参数的Class
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
// 获取 ThreadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 往集合里面添加 SubscriberMethod ,解析方法注解所有的属性
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");
}
}
}
执行完subscriberMethodFinder.findSubscriberMethods(subscriberClass);会通过类对象的 class 去解析这个类中的所有 Subscribe 注解方法的所有属性值,一个注解方法对应一个 SubscriberMethod 对象,包括 threadMode,priority,sticky,eventType,method。效果如下图:
![](https://img.haomeiwen.com/i20061149/5ed098ace03d1c69.png)
接下来看subscribe这个方法,该方法把subscriber,SubscriberMethod分别存好,存入如下两个集合:
//key 是 Event 参数的类 -> 上面的String.class
//value 是存放Subscription的集合 Subscription里面包含两个类 一个是subscriber订阅者(反射执行对象),一个是SubscriberMethod 注解方法的所有属性参数值
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// key 是所有的订阅者
// value 是所有订阅者里面方法的参数的 class,eventType
private final Map<Object, List<Class<?>>> typesBySubscriber;
subscribe方法如下:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//subscriber MainActivity eventType = String
Class<?> eventType = subscriberMethod.eventType;
//将MainActivity 和 SubscriberMethod 再次封装
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//获取订阅了此事件类的所有订阅者列表
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
//线程安全的ArrayList
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;
}
}
//通过subscriber 获取 List<Class<?>>
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);
}
}
}
subscriptionsByEventType 集合架构图如下:
![](https://img.haomeiwen.com/i20061149/9c8f292278f847fa.png)
EventBus post代码
遍历刚刚的map,拿到map的内容,通过反射进行方法的调用
public void post(Object event) {
//event:"发送EventBus事件,任何类型都可以。"
//currentPostingThreadState 是一个 ThreadLocal
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 {
//循环遍历队列,发送单个事件调用postSingleEvent
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 String.class
Class<?> eventClass = event.getClass();
//是否找到订阅者
boolean subscriptionFound = false;
// 是否支持事件继承,默认true
if (eventInheritance) {
//查找eventClass 所有的父类和接口
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
//依次向eventClass的父类或接口的订阅方法发送事件
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));
}
}
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//得到Subscription列表
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
//遍历 subscriptions
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;
}
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);
}
}
网友评论