介绍
EventBus
是一种用于Android的发布/订阅事件总线。在我们开发中经常将其应用于Activity
之间,Fragment
之间的通讯传值等。它能达到简化组件间的通信,以及解耦事件的发送者和接受者的作用。
EventBus
使用十分简单,在需要发送数据的地方调用post
方法,并将数据对象传入
EventBus.getDefault(this).post("test");
在我们期望接受到数据的地方,注册EventBus
,并写一个带有@Subscribe注解的方法,该方法只有一个参数,并且其数据类型与post
方法发送的数据类型一样。该方法就会接收到post发送的数据。
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
EventBus.getDefault().register(this);
}
@Subscribe()
public void receiveValue(String msg){
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
源码分析
基于EventBus3.1.1
如上,EventBus
有三个关键节点,register
注册、post
发送和unregister
取消注册。这里就根据这三个节点来简单分析下源码。
register注册流程
首先通过getDefault
方法获取EventBus单例对象
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
下面是register
方法,该方法是注册给定的用来接收事件的subscriber
订阅者。
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
首先我们看到,调用了subscriber.getClass()
方法得到了订阅者的class对象,如上面的例子我们得到的就是Activity的class对象。这里又将这个class对象传到findSubscriberMethods
中,findSubscriberMethods
的作用是找到订阅者中所有@Subscribe注解标记的方法,将其封装成SubscriberMethod
对象并将其添加到集合中返回。
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;
}
}
首先会去METHOD_CACHE这个Map中取订阅者的方法集合,如果存在就将其直接返回。如果没有缓存,再去查找。ignoreGeneratedIndex
属性值默认为false,这个变量在初始化SubscriberMethodFinder
对象时传入
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
所以,此时执行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);
}
这里先初始化FindState
对象,并调用其initForSubscriber
方法为FindState
的clazz
属性赋值为订阅者的class
对象,如下
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
那么此时while (findState.clazz != null)
判断就成立了,再执行getSubscriberInfo
方法获取subscriberInfo
private SubscriberInfo getSubscriberInfo(FindState findState) {
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;
}
上面在initForSubscriber
方法中为subscriberInfo
赋值为空,而subscriberInfoIndexes
属性在实例化SubscriberMethodFinder
对象时通过EventBusBuilder
对象传入,其值也为空。所以这里的if (findState.subscriberInfo != null)
条件不成立,继续执行else
分支的findUsingReflectionInSingleClass
方法。
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 (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");
}
}
}
首先获取所有声明在订阅者类中的方法数组methods
,然后遍历methods
数组,获取方法的修饰符modifiers
,判断语句(modifiers & Modifier.PUBLIC) != 0
通过修饰符和PUBLIC
对应的值进行按位与运算来判断方法的修饰符是否为PUBLIC
,不等于0即为PUBLIC
;判断语句(modifiers & MODIFIERS_IGNORE) == 0
,其中MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
这个MODIFIERS_IGNORE
的值与modifiers
按位与即判断修饰符是否是MODIFIERS_IGNORE
中的任意一个,结果为0即没有这些修饰符。所以经过这个判断,即保证了@Subscribe
注解的方法必须是public
,非静态以及非抽象的方法。
进入到if
分支,通过getParameterTypes
获取到方法的参数类型数组parameterTypes
,判断数组长度为1时继续执行,否则抛出异常,也就是这里限制了@Subscribe
方法只能有一个参数。然后获取方法上的@Subscribe
注解,通过parameterTypes[0]
获取到了方法参数的类型eventType
。if (findState.checkAdd(method, eventType))
这个判断的checkAdd
方法做了两层检查,即判断该方法是否已经添加到集合中了,返回true即没有添加过,继而获取到注解上声明的线程threadMode
,并将method
方法名、eventType
参数类型、threadMode
线程、priority
优先级、sticky
粘性封装成SubscriberMethod
对象添加到findState.subscriberMethods
集合中。到这里,subscribe
方法中findSubscriberMethods
查找订阅方法的流程执行结束,并得到了List
<SubscriberMethod> 格式的集合。遍历前面得到的集合并调用Subscribe
方法
// 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);
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);
}
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);
}
}
}
首先将subscriber
订阅者对象和SubscriberMethod
订阅方法对象封装成Subscription
对象。在该方法中建立了两个Map关联关系
,第一个:以事件类型为key
,CopyOnWriteArrayList<Subscription>
为value
存到subscriptionsByEventType
这个Map
中,这样就建立了 eventType
事件类型和CopyOnWriteArrayList<Subscription>
((订阅者对象以及订阅者类中的订阅方法)的对象的集合)。第二个:以订阅者为key
,以订阅者类中所有@Subscribe
方法的参数类型(即订阅的事件类型)的集合为value
存到typesBySubscriber
这个Map
中。
至此register流程就结束了,这里主要的操作就是找到订阅类中注解为@Subscribe
的并且修饰符为public
非静态非抽象且只有一个参数的方法,将其封装为SubscriberMethod
添加到集合中保存起来。
post发送流程
post
方法将给定的event
事件发送到Event bus
/** Posts the given event to the event bus. */
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;
}
}
}
首先获取PostingThreadState
对象,这个对象中封装了发送相关的状态,如eventQueue
为事件集合,这里将event
事件添加到这个集合中。判断isPosting
为false
表示当前未处于发送状态,再将当前是否处于主线程赋值给isMainThread
属性,判断当事件集合不为空时,调用postSingleEvent
方法发送集合中的第一个事件。
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));
}
}
}
eventInheritance
属性代表EventBus
是否会考虑event
事件的继承结构,当该值为true
时发送一个事件,注册了这个事件父类的方法也会收到通知。不管该值为true
或false
都会调用到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;
}
通过发送的事件类型从subscriptionsByEventType
中获取对应的subscriptions
集合。遍历subscriptions
集合,调用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 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);
}
}
判断订阅方法指定的执行线程,回调到指定线程中执行订阅方法,即调用invokeSubscriber
方法
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);
}
}
最后通过反射调用subscriber
对象中的method
方法,并将event
事件传递到方法中,至此post发送流程就结束了。通过Post发送事件的eventType
类型从Register流程中构造的subscriptionsByEventType这个Map对象中获取到对应的订阅者以及其中订阅方法的集合,遍历集合再通过反射来执行订阅者中的订阅方法。
unregister取消注册流程
将订阅者从所有事件类中取消注册。
/** 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 {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
遍历事件类型集合subscribedTypes
,调用unsubscribeByEventType
方法,并从subscribedTypes
移除订阅者subscriber
。
/** 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--;
}
}
}
}
根据事件类型获取到subscriptions
集合,遍历集合,并将当前订阅者subscriber
对应的Subscription
对象从集合中移除。取消注册流程比较简单,从typesBySubscriber
中移除subscriber
,从subscriptions
集合中将subscriber
对应的Subscription
对象移除。