1. EventBus 源码简单解析
1.1 初始化
使用单例
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;
}
1.2 事件的注册
public void register(Object subscriber) {
// 拿到观察者的Class
Class<?> subscriberClass = subscriber.getClass();
// 找到该类中所有被@Subscriber修饰的方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
// 注意保证线程安全,这个方法可能在多个线程中同时调用
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
subscribe(subscriber, subscriberMethod); 生成订阅关系
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 拿到这个subscriber 的Event Type
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 以这个事件类型为Key,拿到这个事件的所有订阅者
// subscriptionsByEventType 的数据类型是 Map<Class<?>, CopyOnWriteArrayList<Subscription>>
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 把观察者放入队列 注意 subscriptions.contains(newSubscription)
// subscriptions 的 equal 和 hashcode 方法被重写了,这要这个事件的方法和方法所在的实例相同就是同一个
// 按照优先级的顺序排列
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;
}
}
// 维护这个观察者和这个观察者所观察的所有事件之间的关系
// 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);
}
在注册的时候要注意两个重要的数据结构
/*维护的是观察者和该观察者中所有被事件触发的方法*/
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
/*维护这个观察者和这个观察者所观察的所有事件之间的关系*/
private final Map<Object, List<Class<?>>> typesBySubscriber;
还有几个重要的方法要注意
subscriberMethodFinder.findSubscriberMethods(subscriberClass)
找到这个类的所有被事件触发的方法,即找到被@Subscriber修饰的方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 先找缓存中有没有
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 分两步是从索引中找还是通过反射的方法找
// ignoreGeneratedIndex 是否忽略索引
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
}
// 判断结果是否放入缓存
我们具体关注一下 findUsingInfo 方法
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
/** 下面的这两句是初始化准备,有点长
第一句 FindState findState = prepareFindState();
prepareFindState 是获取一个 FindState
private static final FindState[] FIND_STATE_POOL = new FindState[4];
FindState[] 是长度为4 的数组
如果数组为空就重新new 一个,如果在该位置不为空
就把该位置的对象返回,同时吧该位置置空
private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new FindState();
}
第二句 findState.initForSubscriber(subscriberClass);
只是把 subscriberClass 传入FindState ,这个是一个内部类
*/
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
// 开始查找 ,注意这是一个循环,从子类一直找到最上面的父类
while (findState.clazz != null) {
/*
getSubscriberInfo 方法的主要部分如下 :
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfoIndex 是通过编译时注解自动生成的 类 在下面会着重讲到
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
*/
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();
}
/**
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle(); 把 findState 内部的一些字段重新初始化循环使用
synchronized (FIND_STATE_POOL) { // 把 findState放回池子里面
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
*/
return getMethodsAndRelease(findState);
}
subscriberMethod.eventType 找到事件的Type
/*SubscriberMethod 的内部结构*/
public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
this.method = method;
this.threadMode = threadMode;
this.eventType = eventType; // 就是观察者的全类名
this.priority = priority;
this.sticky = sticky;
}
1.3 事件发送 POST
使用POST来发送事件
public void post(Object event) {
/**
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
PostingThreadState 的内部结构
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>(); // 事件队列
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
**/
PostingThreadState postingState = currentPostingThreadState.get();
// 将要发送的事件放到发送事件队列中去
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
// 判断是否在发送
if (!postingState.isPosting) {
/**
private boolean isMainThread() {
return mainThreadSupport != null ? mainThreadSupport.isMainThread() : true;
}
MainThreadSupport 是一个接口,有一个在android端的实现AndroidHandlerMainThreadSupport
**/
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;
}
}
}
重点看一下 postSingleEvent 方法是怎么来post事件的
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
/* eventInheritance 是否事件冗余
eventInheritance : true 的话,会发送到该事件的父类的@Subscriber 方法
eventInheritance : false 值发送到当前类的 @Subscriber 方法
*/
if (eventInheritance) {
/**
lookupAllEventTypes 方法的主要部分如下 :
拿的该类的所有接口和父类以及父类的接口
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
**/
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);
}
}
具体事件的发送在 postSingleEventForEventType()方法内
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
/* 加锁获取该事件类型的所有观察者,该方法可能在不同线程中同时调用*/
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
/* subscriptions 不为空的话继续处理 */
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;
}
更加细致的处理过程在 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);
}
}
具体看一个 ASYNC 的case :
private final AsyncPoster asyncPoster;
EventBus(EventBusBuilder builder) {
....
asyncPoster = new AsyncPoster(this);
....
}
/**
interface Poster {
/**
* Enqueue an event to be posted for a particular subscription.
*
* @param subscription Subscription which will receive the event.
* @param event Event that will be posted to subscribers.
*/
void enqueue(Subscription subscription, Object event);
}
**/
class AsyncPoster implements Runnable, Poster {
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
// 在线程池中执行
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
// 从事件队列中拿一个 PendingPost
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
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);
}
}
1.4 解除注册
/* synchronized */
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
/**
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--;
}
}
}
}
**/
unsubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
}
2. 使用运行时注解生成索引
具体所用到的技术 :
EventBus 生成的代码如下面的样式 :
/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;
static {
SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();
// 每有一个订阅者类,就调用一次putIndex往索引中添加相关的信息
putIndex(new SimpleSubscriberInfo(com.study.sangerzhong.studyapp.ui.MainActivity.class, true, new SubscriberMethodInfo[] {
new SubscriberMethodInfo("onEvent", com.study.sangerzhong.studyapp.ui.MainActivity.DriverEvent.class, ThreadMode.POSTING, 0, false),
// 类中每一个被Subscribe标识的方法都在这里添加进来
}));
}
// 下面的代码就是EventBusAnnotationProcessor中写死的了
private static void putIndex(SubscriberInfo info) {
SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
}
@Override
public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
if (info != null) {
return info;
} else {
return null;
}
}
}