EventBus源码分析
EventBus 是一个事件总线框架,解决了组件之间通信的问题。使用了观察者模式。使代码更加简洁
简单使用
1.引入依赖
compile 'org.greenrobot:eventbus:3.1.1'
2.定义事件
public class MessageEvent {
private Object msg;
public MessageEvent(Object msg) {
this.msg = msg;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
@Override
public String toString() {
return "MessageEvent{" +
"msg=" + msg +
'}';
}
}
3.注册与反注册
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
mTextView = findViewById(R.id.tv);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
4.在某个地方发送事件
EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));
5.在注册页面接收事件
@Subscribe(threadMode = ThreadMode.MAIN, priority = 100, sticky = false)
public void onMessageEventPost(MessageEvent messageEvent) {
Log.e(TAG, "onMessageEventPost: " + messageEvent.getMsg().toString());
mTextView.setText(messageEvent.getMsg().toString());
}
@Subscribe(threadMode = ThreadMode.MAIN, priority = 150, sticky = false)
public void onMessageEvent(MessageEvent messageEvent) {
Log.e(TAG, "onMessageEvent: " + messageEvent.getMsg().toString());
mTextView.setText(messageEvent.getMsg().toString());
}
注册分析
EventBus.getDefault().register(this);
这行代码都做了什么呢,大眼一看感觉好像是用的单例模式构造对象。
创建EventBus对象
/** Convenience singleton for apps using a process-wide EventBus instance. */
/*使用双重锁校验创建EventBus对象*/
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
注册
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* 参数类型是Object,可以接收各种类型。
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
// 使用反射获取到类的字节码文件
Class<?> subscriberClass = subscriber.getClass();
// 通过反射获取该类中所有 包含 @Subscribe 注解的方法,得到的是一个集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
// 上锁
synchronized (this) {
// 循环遍历所有的方法,进行订阅
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 订阅 subscriber 在这里表示就是MainActivity
// subscriberMethod 在这里表示方法有两个 onMessageEventPost onMessageEvent
subscribe(subscriber, subscriberMethod);
}
}
}
来到了SubscriberMethodFinder
类中,从类名直接来看,是订阅者方法搜寻者,通过类的字节码文件找到所有订阅者的方法,这个类是在Eventbus的构造方法中创建的。
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 这里使用Map做了一个缓存,先从Map中找,如果没有在通过反射去遍历寻找。能提高效率
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
// 如果Map中存在,就直接取出来
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGenerateIndex这个值表示是否忽略注解器生成的MyEventBusIndex
// 这个值默认是false,表示可以通过EventBusHandler来设置他的值
if (ignoreGeneratedIndex) {
// 利用反射来获取订阅类中所有的订阅方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 第一次走到这里 从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
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> 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);
}
通过反射获取订阅类中的订阅方法信息
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();
// 方法只能是 public ,如果设置成private 和 static abstract 的话将会报错
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 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");
}
}
}
当我们获取到所有的标有 @subscribe 注解的方法之后,就要开始进行订阅subscribe 操作,主要做的工作就是解析所有 subscriberMethod 的eventType,然后解析成Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;的格式,key 为参数类型的class,value是保存了Subscription的一个列表,Subscription包含两个属性,一个是subscriber(订阅者类),一个是subscriberMethod,就是注解方法
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取方法参数的class ,在我们的这里demo中表示 MessageEvent.class
Class<?> eventType = subscriberMethod.eventType;
// 构建一个 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// subscriptionsByEventType 是一个Map,key是方法参数的Class:MessageEvent.class.value 是这里相当于做了一个缓存操作
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;
}
}
// 通过 subscriber 获取 List<Class<?>> typesBySubscriber 也是一个Map,key保存的是订阅者,value是所有订阅者里面方法参数的Class
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);
}
}
}
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
postToSubscription(newSubscription, stickyEvent, isMainThread());
}
}
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
这个Map的数据结构,subscriber -> MainActivity, subscriberMehtod -> onMessageEventPost
粘性事件(sticky event):普通事件是先注册,然后发送事件才能收到;而粘性事件,在发送事件之后再订阅该事件也能收到。此外,粘性事件会保存在内存中,每次进入都会去内存中查找获取最新的粘性事件,除非你手动解除注册。
post()发送分析
EventBus.getDefault().post(new MessageEvent("嘿嘿嘿"));
// ThreadLocal 是一个创建线程局部变量的类,,通常情况下我们创建的变量是可以被任何一个线程访问的,但是ThreadLocal创建的变量只能被当前线程访问,其他
// 线程无法访问和修改。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
/** Posts the given event to the event bus. */
public void post(Object event) {
// event 就是我们发送的时间 MessageEvent
// 获取到当前线程的变量数据
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,就是 MessageEvent.class
Class<?> eventClass = event.getClass();
// 是否找到订阅者
boolean subscriptionFound = false;
// 是否支持事件继承,默认为true
if (eventInheritance) {
// 获取到所有的事件的父类和接口
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) {
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) {
// 得到 subscription 列表,这个对象里包含两个部分,见上图
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 {
// 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);
}
}
BACKGROUND 与 ASYNC 的区别:
前者中的任务是串行调用,后者是异步调用。
总结:
事件的发送和接收,主要是通过subscriptionsByEventType这个列表,Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
。我们将订阅即接收事件的方法存储在这个列表,发布事件的时候在遍历列表,查询出相对应的方法并通过反射执行。
网友评论