前言
- Eventbus是组件内和组件之间的事件传递,与Intent和Broatcast有什么区别,优劣势在哪,原理如何实现, 使用反射对性能影响?
- Intent 传递大数据时导致TransactionTooLargeException,Broadcast 接受事件之后无法指定运行线程,以及这些实现方式的繁琐,耦合
- 使用简单,可以指定接收事件的函数运行的线程,解耦,传递大量数据的Event时不会崩溃
原理
- 获取注册对象中通过 @Subscribe 注解的方法,保存在list列表
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
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;
}
}
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
findUsingReflectionInSingleClass(findState);
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
findUsingReflectionInSingleClass(findState);
}
- 遍历注解方法列表,逐个绑定到当前对象
2.1 根据注解方法事件对象类型,构建map
2.2 根据注册对象(Activity)保存当前对象中存在的事件类型,构建map
2.3 如果当前注解方法接收的事件是粘性事件,则根据当前方法的参数类型(也就是事件类型)从粘性事件map缓存中(postSticky时保存)获取粘性事件信息,如果存在则执行当前注解方法(实现延迟响应事件的原理)
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod)
}
//绑定 SubscriberMethod 到 当前对象
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
/**
* 1.根据注解方法中的参数类型(event)作为key,保存所有参数是 event 的注解方法 的封装对象(包含注解方法所在的类)
* 例如:Activity1中存在注解方法 method1(String msg),method2(String msg) 那么Activity1和method1会打包成一个对象保存,Activity1和method2又会打包一个对象保存
*
* map.put("String.class", List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)) )
* map.put("Int.class", List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)) )
* 备注:这里的注册对象其实是注解方法和
*/
/**
* 重点对象
* 缓存集合 key = 事件对象类型(event.class),value = 所有参数是 event 的注解方法 的封装对象(包含注解方法所在的类)
* 可以理解为对于 String.class 类型的事件,有多个 Activity1,Activity2... 中存在接收的方法 (可以结合广播理解,一个 action,可以有多个广播接收器能够接收)
*/
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
Class<?> eventType = subscriberMethod.eventType
Subscription newSubscription = new Subscription(subscriber, subscriberMethod)
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType)
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
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription)
break
}
}
/**
* 步骤1总结
*
* @Subscribe(threadMode = ThreadMode.MAIN)
* public void updateUI(String event) {
* }
*
* 到这一步为止,会根据 String.class 作为key 保存所有方法参数为String的封装对象(理解为 List(Subscription(Activity1&m1),Subscription(Activity1&m2),Subscription(Activity2&m1)))
* 有什么作用呢?等下 post(String event) 的时候就可以根据这个 String.class 作为key找到 所有的已经注册的对象,然后挨个调用这些对象中的 @Subscribe 方法
*/
/**
* 2.根据当前注册对象(Activity)作为key,保存所有事件类型。形成一个map
* map.put("Activity1",List(String.class,Int.class..))
* map.put("Activity2",List(String.class,Int.class..))
*/
/**
* 重点对象
* 缓存集合 key = 当前注册对象,value = 事件对象类型列表
* 可以理解为在 Activity1 中存在多个注解方法,他们的事件类型为 String.class ,Int.class
*/
private final Map<Object, List<Class<?>>> typesBySubscriber
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber)
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>()
typesBySubscriber.put(subscriber, subscribedEvents)
}
subscribedEvents.add(eventType)
/**
* 步骤2总结
*
* 到这一步为止,会根据当前注册对象 Activity 作为key 保存本类中所有注解方法的事件类型(也是方法参数类型)
*
* 有什么作用呢?
* 1.用于查询是否已经注册了当前对象 isRegistered(Object subscriber){ return typesBySubscriber.containsKey(subscriber)
* 2.解绑注册 unregister(Object subscriber) 的时候可以找到所有的事件类型,(结合 subscriptionsByEventType )然后再根据事件找到 已经注册对象的列表,移除当前注册的对象
*/
/**
* 3.判断当前注册对象中的注解方法是否为粘性事件,如果粘性事件,从粘性事件缓存中取出粘性事件相关的信息
*/
/**
* 重点对象
* 缓存集合 key = 事件对象类型,value = Object(事件)
* 粘性事件单独存在一个Map集合中,这也是为什么可以先发送粘性事件,然后在注册接收,因为它存放在缓存map中,只要不清除,它就一直在
* map.put("String.class", Object 粘性事件1 )
* map.put("String.class", Object 粘性事件2 )
* map.put("Int.class", Object 粘性事件1 )
* map.put("Int.class", Object 粘性事件2 )
*/
private final Map<Class<?>, Object> stickyEvents
if (subscriberMethod.sticky) {
if (eventInheritance) {
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)
}
}
}
- register主要是保存一些数据,为后续post发送事件做一些铺垫作用
- 跟着注释走主要路线就行,首先通过事件类型,找到已经注册的列表,(注册列表在每次注册的时候添加),找到注册列表之后挨个发送当前事件,怎么发送当前事件?找到注册对象的目标method,根据method指定的运行线程,按需要做一些线程切换的操作,然后通过反射调用 method.invoke(方法所在对象,方法参数)
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;
}
}
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
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));
}
}
}
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;
}
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 {
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);
}
}
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);
}
}
- 粘性事件(Sticky)和普通事件相比,就多了一步将粘性事件保存到缓存 map 中,原来粘性事件的原理这么简单,发送的时候保存到缓存map中,延时(需要时)再取,实现了可以先发送事件,后注册的效果。
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
post(event);
}
- 解绑注册也是比较简单的,首先通过当前对象找到本类中所有的事件类型,再根据某个事件类型找到已经注册该事件的对象列表(如:activity1,activity2…),然后根据比较当前对象是否存在列表中,如果存在,从列表中移除,释放资源
//解绑注册,释放资源等
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())
}
}
//根据事件类型解绑已注册对象
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType)
if (subscriptions != null) {
int size = subscriptions.size()
for (int i = 0
Subscription subscription = subscriptions.get(i)
if (subscription.subscriber == subscriber) {//已注册列表等于当前对象时
subscription.active = false
subscriptions.remove(i)
i--
size--
}
}
}
}
分析不会崩溃原因
- Intent 方式实际上底层parcel对象在不同activity直接传递过程中保存在一个叫做“ Binder transaction buffe ”的缓冲区,并且这个缓冲区大小有限制,不能超过1M。
EventBus 不存在将数据放在什么缓冲区中,普通事件直接拿到事件对象,找到需要调用的方法直接调用即可,简单的方法参数传递; 而粘性事件,将数据缓存在内存中,保存在map,除非是内存爆炸,不然是没有大小限制的说法。因此说EventBus可以传递大数据
- EventBus 通过注解的方式指定接收事件的运行线程,在注册的时候将注解信息保存起来,当post事件的时候拿到注册时保存的注解信息(运行线程),通过不同的 ThreadMode 做不同的处理,如开启工作线程执行接收事件的方法,或者通过handler方式将事件运行在主线程中,以此达到指定线程运行方法的目的