概述
EventBus, 作者的解释是一个为Android系统优化的事件订阅总线(EventBus is a publish/subscribe event bus for Android and Java.)。它可以在不同线程、不同组件间进行事件传递。可以很好地完成系统原生的 Intent以及 Handler的一些工作,在开发过程中运用还是比较广。下面是要分步讲解的内容:
*注册与订阅
*事件发送
*注销
官方源码:EventBus
一、注册与订阅
这里就不讲使用了,使用还是比较简单的。但要追踪源码,所以把基本使用方式贴出来:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册
EventBus.getDefault().register(this);
// SecondActivity
EventBus.getDefault().post(EventMessage.getInstance("发射"));
}
// POSTING : 在发布时的线程执行
// MAIN : 始终在主线程中执行
// MAIN_ORDERED : 在主线程中执行,不过需要排队
// BACKGROUND : 始终在子线程中执行
// ASYNC : 异步,始终在另一个子线程中执行
@Subscribe(threadMode = ThreadMode.MAIN)
private void receiveMessage(EventMessage eventMessage){
Log.d("MainActivity", "msg = " + eventMessage.mMsg);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 注销
EventBus.getDefault().unregister(this);
}
}
看看这个 getDefault() 静态方法干了啥:
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance;
if (instance == null) {
instance = EventBus.defaultInstance = new EventBus();
}
}
}
return instance;
}
其实老司机不用点进来也能知道,是单例模式拿了 EventBus的对象。下面还是看注册方法 register(this) 干了啥吧 :
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 注释 1 获取该订阅者的所有订阅方法,看命名有点像反射,点进去看看
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 注释 2 for 循环将所有方法进行保存注册
subscribe(subscriber, subscriberMethod);
}
}
}
看注释 1,获取了一个列表,从命名来看应该是用了反射获取了订阅者(Activity)的所有订阅方法。那么就点进注释 1处 findSubscriberMethods(subscriberClass)这个方法看一下:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 从缓存中拿方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 注释 3 是否使用反射获取方法
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
.........
return subscriberMethods;
}
}
可以看到,上面使用了缓存。无缓存的情况下有两种获取订阅方法的方式,一种是从编译生成的对象里获取,另一种就是反射。我们继续追踪,看看反射的方法 findUsingReflection(subscriberClass) :
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 注释 3
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
看来还没完,我们继续追踪注释3处的 findUsingReflectionInSingleClass(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/14
.......
}
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) {
// 注释 4 获取订阅者里所有被打上 Subscribe.class注解的方法
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 注释 5 获取注解里的参数
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()));
}
}
}
......
}
}
}
上面代码省略掉了一些细节处理。我们看到,方法里用反射获取订阅者里的所有方法。然后在注释 4 处获取了其中被注解 Subscribe.class 标记的方法,往下连同注解的参数一并获取保存。好了,订阅方法的获取已经看到了。走得太深了,我们回到最初注册的方法里,看拿到订阅方法列表后是怎么处理的:
// register()
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, 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<>();
// 注释 6 将打包在 ArrayList(CopyOnWriteArrayList) 列表里的方法集 put 进 HashMap中
// key值是 消息类型 eventType , value值是装有方法的列表
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) {
// 注释 7 根据优先级存入方法
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
// 注释 8 将所有消息类型存入另一个 HashMap中,用于注销时清除上面事件列表的 HashMap
// key值是 订阅者 subscriber,value值是订阅者里所有事件类型的列表
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
// 粘性事件的处理
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);
}
}
}
从上面注释 6中可以看到,通过反射获取的订阅者方法列表被保存在了一个 HashMap中,key值是消息类型,Value值是方法列表。另外,下面注释 8中可以看到,该HashMap的key 值则被当成 value值存放在另外一个 HashMap中(typesBySubscriber),而用订阅者subscriber作为了 Key值。目的是在注销订阅者时,可以根据订阅者取出里面的所有消息类型作为Key值,对保存在HashMap中的方法列表进行清除。注销部分后面会讲到。
二、发送消息
下面来看看发送消息的过程:
/** Posts the given event to the event bus. */
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
// 注释 9 先将事件放入列表中
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()) {
// 注释 10 ,while 循环从列表中取出事件
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
可以看到上面注释 9,事件发送后是先放入列表中的,然后注释 10 while循环处将事件取出进行下一步处理。我们再往下看postSingleEvent() 这个方法:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) { // 注释 11,继承关系的判断
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 {
// 注释 12,参数继续传递,往下执行
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
}
上面注释 11处是一些继承关系的判断和处理,就不细讲了。看注释12,我们继续往下看 postSingleEventForEventType()这个方法:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 注释 13 ,从注册时的 HashMap 中取出注册方法
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted;
try {
// 注释 14 ,往下执行
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;
}
跳过一些细节,看注释 13,这里根据消息类型eventClass从注册时保存进HashMap中的方法列表取出。我们继续往下看注释 14 postToSubscription()这个方法:
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
// 注释 15, POSTING : 在发布时的线程执行
case POSTING:
invokeSubscriber(subscription, event);
break;
// 注释 16, MAIN : 始终在主线程中执行
case MAIN:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
//注释 17, MAIN_ORDERED : 在主线程中执行,不过需要排队
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;
// 注释 18, BACKGROUND : 始终在子线程中执行
case BACKGROUND:
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
// 注释 19, ASYNC : 异步,始终在另一个子线程中执行
case ASYNC:
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
好了,看上面。到了事件发送线程变换的地方了。这里有一个 switch 语句,用于判断订阅方法的线程模型。这5个线程模型的意思上面也做了简要的注释。除了 POSTING模式外,其他模式都有可能需要切换线程。需要切换线程时,就像上面会有一个 enqueue的的操作,将事件放入线程池中切换线程执行。现在我们来继续追踪上面的 invokeSubscriber() 这个方法:
void invokeSubscriber(Subscription subscription, Object event) {
try {
// 注释 20 反射调用订阅者的方法
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
好了,终于看到最后了。反射调用了注册时保存在 HashMap中的 CopyOnWriteArrayList列表里的订阅方法。这样,事件发送就得到执行了。
三、注销
最后来看看注销:
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
// 注释 21,从集合中取出 Key值
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
// 注释22, 再根据上面注释去除的 Key值从HashMap中移除方法列表
unsubscribeByEventType(subscriber, eventType);
}
// 注释 23,最后,再将该订阅者移除
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
可以看到上面的方法注释 21。typesBySubscriber是注册时使用到的一个HashMap。这就是前面讲注册流程时说到的,第一个HashMap用来装第二个 HashMap的 Key值。目的就是在注销时,可以根据这个 Key值移除第二个 HashMap的 Value值,这个Value值也就是将被注销的订阅者的方法列表。
上面获取到 Key值(K消息类型)之后,在注释 23处调用了移除HashMap里订阅者方法列表的函数。移除方法在下面,不再细说。
// 从 HashMap中移除订阅者方法列表
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--;
}
}
}
}
最后,贴一张大概的框架草图吧。不好看也不详细,就当做一下看完源码后的一个小汇总:
EventBus.png
其实上面只是对 EventBus这个框架作了一个大概的流程解析。这个框架其实还是挺完善的,处理了大量的细节。例如使用了缓存、非反射形式的注册等等。还是做了不少打磨的。
网友评论