转载请说明出处: https://www.jianshu.com/p/33e58e748bb5
使用方式
- 在Activity的onCreate中调用EventBus.getDefault().register(this)
- 在Activity里面解绑EventBus.getDefault().unreister(this)
- 想要发送一个事件时通过EventBus.getDefault().post("test_content");
public void register(Object subscriber) {
// 首先获得class对象
Class<?> subscriberClass = subscriber.getClass();
// 通过 subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod
// 里包含了这个方法的 Method 对象,以及将来响应订阅是在哪个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优
// 先级 priority ,以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的所有 Subscriber 注解方法属性。
// subscriber对象中解析好的方法集合
1. List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 订阅这个对象中的方法
2. subscribe(subscriber, subscriberMethod);
}
}
}
1. 解析注解
- 通过反射解析我们所注册的类中所有带有@Subscriber注解的方法
- 将注解中所有数据打包成这个对象: new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()) - 将这个对象放入全局的集合中, findState.subscriberMethods.add(subscriberMethod对象)
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 先从缓存里面读取,订阅者的 Class
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 支持编译时注解, 引入EventBus的APT即可
// ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex。
// ignoreGeneratedIndex的默认值为false,可以通过EventBusBuilder来设置它的值
if (ignoreGeneratedIndex) {
// 通过运行时反射+注解的方式去查找Class内的方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 通过编译时注解从伴生类中去查找Class内的方法信息
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;
}
}
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 寻找某个类中的所有事件响应方法, 将找到的方法放入findState这个对象中
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass(); // 继续寻找当前类父类中注册的事件响应方法
}
// 返回findState这个对象, 其中包含了subscriberClass这个Class中所有@Subscriber注解标注的方法
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 循环所有方法
for (Method method : methods) {
// 获取方法访问修饰符
int modifiers = method.getModifiers();
// 找到所有声明为 public 的方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();// 获取参数的的 Class
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");
}
}
}
执行订阅
- for循环遍历所有的SubscriberMethod(), 将所有eventType然后按照要求解析成Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType的格式
- subscriptionsByEventType :
- key: eventType的class
- value: 该eventType在post时, 所需要响应的对象和其中订阅了该eventType的方法的集合
- typesBySubscriber:
- key:订阅者的对象
- value: 该对象其中所有带有@Subscriber注解的方法集合
// key: eventType的class
// value: 该eventType在post时, 所需要响应的对象和其中订阅了该eventType的方法的集合
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
// key: 订阅者的对象
// value: 该对象其中所有带有@Subscriber注解的方法集合
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取方法参数的 class
Class<?> eventType = subscriberMethod.eventType;
// 创建一个 又封装了一个Subscription对象
// 其需要的参数为: 1. 订阅者的对象和 2. 其中订阅的方法
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 获取订阅了此事件的所有订阅者信息列表
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 若该eventType没有订阅者列表, 则我们创建一个
if (subscriptions == null) {
// 线程安全的 ArrayList
subscriptions = new CopyOnWriteArrayList<>();
// 添加到Map中
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这个对象中订阅的所有方法的集合
// 方便unregister(this)中通过传入的对象去移除其所对应的方法集合
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);
}
}
}
post
- 判断eventQueue事件队列中是否有事件正在posting, 若没有则post当前event
- 通过遍历subscriptionsByEventType集合回调集合中所有注册了eventType的方法
/** Posts the given event to the event bus. */
public void post(Object event) {
// currentPostingThreadState 是一个 ThreadLocal
PostingThreadState postingState = currentPostingThreadState.get();
// postingState 就是获取到的线程独有的变量数据
List<Object> eventQueue = postingState.eventQueue;
// 把 post 的事件添加到事件队列
eventQueue.add(event);
// 判断队列中是否有事件正在发送, 若没有则post当前事件
if (!postingState.isPosting) {
// 是否是主线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
// 更新postingState的标记位
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
// 若事件队列不为空, 则piosting这个Event
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
Class<?> eventClass = event.getClass();
// 是否找到订阅者
boolean subscriptionFound = false;
// 如果支持事件继承,默认为支持
if (eventInheritance) {
// 查找 eventClass 的所有父类和接口
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
// 依次向 eventClass 的父类或接口的订阅方法发送事件
// 只要有一个事件发送成功,返回 true ,那么 subscriptionFound 就为 true
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));
}
}
}
// 事件分发调用的核心代码
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 通过eventClass来找到需要回调的subscriptions集合
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍历 subscriptions
for (Subscription subscription : subscriptions) {
// 即post的值
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 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);
}
}
unregister
- 通过传入的对象, 找到其类中所有订阅的方法
- 遍历所有方法的eventType, 将其在subscriptionsByEventType中移除
- 最后将其在typesBySubscriber中移除, 从而避免了内存泄露
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
// 获取该对象的所有订阅方法的集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
// for循环每一个eventType
// 将subscriptionsByEventTypeMap中该对象所关联的所有方法全部移除, 防止内存泄露
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
// 将订阅者从列表中移除
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 获取事件类的所有订阅信息列表,将订阅信息从订阅信息集合中移除,同时将订阅信息中的active属性置为FALSE
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) {
// 将订阅信息激活状态置为FALSE
subscription.active = false;
// 将订阅信息从集合中移除
subscriptions.remove(i);
i--;
size--;
}
}
}
}
网友评论