EventBus的使用:
在分析源码前先来回顾一下EventBus怎么用的,开源地址:GitHub
- 在app项目build.gradle中添加依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
- 然后注册订阅者,官方推荐是在onStart和onStop里注册和取消注册
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
- 创建自定义事件,例如:
public static class LoginEvent { }
- 发送事件:
EventBus.getDefault().post(new LoginEvent ());//发送普通事件
EventBus.getDefault().postSticky(new LoginEvent ());//发送粘性事件
- 接收自定义事件
@Subscribe(threadMode = ThreadMode.MAIN, priority = 100, sticky = true)
public void onMessageEvent(LoginEvent event) {};
在Subscribe注解里有三种属性:
- threadMode:用于指定接收事件的方法在哪个线程里执行,有五种类型,ThreadMode.MAIN、ThreadMode.MAIN_ORDERED、ThreadMode.BACKGROUND、ThreadMode.ASYNC;默认值是:ThreadMode.POSTING
- priority:接收事件的优先级,数值越高优先级越高,默认值为0
- sticky: true表示粘性事件,false表示普通事件,粘性事件指的是发出去的,默认值为false
疑问:
- EventBus是如何注册和取消注册的?
- SubScribe注解里的三种属性是在什么时候起作用的?
- 接收事件是如何在不同线程切换执行的?
- EventBus是如何发送和接收事件的?
源码分析:
带着疑问我们开始分析EventBus,首先来看看是如何注册订阅者的:
EventBus.getDefault().register(this);
public class EventBus {
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
}
通过代码可以看到,EventBus.getDefault()返回的是EventBus的单例,接着看看register方法:
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* <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();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
从这个方法的注解我们可以知道:
- 这个方法是用来注册需要接收事件的订阅者
- 如果不再需要接收事件,则需要调用unregister方法取消订阅
- 订阅者里面需要有接受事件的方法,并且使用Subscribe注解
- 这个Subscribe注解可以配置它的threadMode和priority等属性
从代码上看:
- 它首先通过findSubscriberMethods方法分析订阅者的类,获取到该订阅者里所有用于接收事件的方法
- 然后调用subscribe方法将订阅者和这些方法保存起来
那么它是如何通过订阅者类拿到所有用于接收事件方法的? 以及如何保存订阅者和方法的呢?
分析如何通过订阅者拿到所有接收事件的方法:
class SubscriberMethodFinder {
private final boolean ignoreGeneratedIndex;
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查找缓存过的方法,如果有的话则直接返回
- 接着通过ignoreGeneratedIndex来判断是走findUsingReflection还是findUsingInfo,通过上下文可以看到ignoreGeneratedIndex的值默认是false,根据源码的注释,这个字段如果为true,表示忽略生成的索引,强制使用反射来获取类中的方法
- 上面所说的索引,其实是指使用eventbus-annotation-processor在编译时候去解析注解获取订阅者里订阅的事件方法,从而避免使用反射获取订阅方法,以提高效率
- 然后判断订阅的方法是否为空,为空则抛出异常
- 最后将订阅的方法缓存起来
接下来我们再来看看findUsingInfo里的方法,它和findUsingReflection里的内容差不多,只是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);
}
- prepareFindState方法中主要是先从FIND_STATE_POOL获取缓存的FindState对象,没有的话就new FindState(),从而复用已有的FindState节约资源
- 接着通过getSubscriberInfo方法来获取findState.subscriberInfo,这个对象只有使用了【eventbus-annotation-processor】在编译时解析处理过订阅者方法才不为null,其他情况都是返回null,也就是编译时有解析过订阅者的方法,则不在运行时使用反射获取
- 所以接着就会进入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");
}
}
}
- 先反射拿到类里的所有方法
- 判断该方法是不是合法的,必须是public,不能是static静态方法以及abstract抽象方法,不合法则抛出异常
- 然后获取方法里的参数,参数只能有一个,如果超过则抛出异常
- 接着判断该方式是否有Subscribe注解,没有的话则忽略
- 判断有没有添加过,没有添加过则添加,并将【方法名】【事件类型】【threadMode线程模式】【优先级priority】【sticky是否粘性事件】这些信息保存到SubscriberMethod对象里
在获取完订阅者里所有订阅方法后,接着就是将这些方法通过EventBus.java@subscribe方法一个个保存起来:
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);
}
}
}
- 将订阅者和对应的接收事件方法封装到新的Subscription对象里,表示一个订阅事件
- subscriptionsByEventType是个map对象,eventType作为key值,所有订阅了该事件的Subscription集合作为value
- typesBySubscriber也是个map对象,subscriber作为key值,该订阅者里订阅的所有事件集合作为value
- stickyEvents,是个map类,保存了所有的粘性事件,事件类型event.getClass作为key,事件Object作为Value
- 先从中subscriptionsByEventType通过事件类型获取该事件所有的订阅者集合CopyOnWriteArrayList,将当前要订阅的事件根据优先级priority保存到CopyOnWriteArrayList中,优先级高的则放在列表前面
- 然后通过typesBySubscriber获取该订阅者订阅的所有事件,并将当前要订阅的事件保存进来
- 如果判断是粘性事件sticky=true,则将之前发送过的粘性消息发送给这个订阅者
- eventInheritance这个字段,默认为true,如果设为true的话,它会去遍历所有粘性事件,只要是当前事件的类或者它的父类粘性事件,都会发送给当前订阅者,设为false,则只处理当前Event类型的粘性事件,可以在一定程度上提高性能
- 处理粘性事件是在checkPostStickyEventToSubscription方法里,这个方法里调用了postToSubscription方法,后面分析消息发送时也会调用到这个方法
到这里EventBus消息的注册过程就结束了,接下来就来分析一下消息发送过程:
EventBus.getDefault().post(new LoginEvent ());//发送普通事件
EventBus.getDefault().postSticky(new LoginEvent ());//发送粘性事件
消息发送有两种方式,一种是发送普通消息调用post方法,一种是发送粘性消息调用postSticky方法,我们先来看看postSticky方法:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
- 在postSticky方法只是将粘性事件保存到stickyEvents集合中,然后还是调用了post方法
接着来看看post方法:
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;
}
}
}
- currentPostingThreadState:是一个ThreadLocal类型,也就是每个线程都维护了一个PostingThreadState对象
- PostingThreadState:包含了当前要处理的事件队列eventQueue(ArrayList),以及isMainThread (是否主线程),isPosting(是否正在传递消息)等信息
- 在post方法中,首先将要处理的消息event加入到队列中
- 接着循环遍历这个事件队列,一个个调用postSingleEvent这个方法进行处理
接着来看看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));
}
}
}
- lookupAllEventTypes:查找该事件类的所有父类和接口
- postSingleEventForEventType:获取该事件所有订阅者,循环遍历发送事件
- 如果没有找到该事件对应的订阅者,则抛出异常NoSubscriberEvent
EventBus.java@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找出所有该事件的订阅者
- postToSubscription:将该消息发送给单个订阅者
EventBus.java@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);
}
}
- 根据配置的threadMode属性,切换到不同线程发送消息:
- ThreadMode.POSTING: 发送事件在哪个线程,就在哪个线程接收事件
- ThreadMode.MAIN:如果发送事件所在线程就是主线程,则直接回调接收事件方法,此时会阻塞当前线程;如果当前不在主线程,则通过Handler发送到主线程执行,不会阻塞当前线程
- ThreadMode.MAIN_ORDERED:直接通过Handler发送到主线程去执行,不阻塞当前线程
- ThreadMode.BACKGROUND:如果当前不在主线程,则直接调用接收事件的方法,如果在主线程,则放入线程池中执行,不管有多少个消息都只占用线程池中1个线程,也就是这里面的消息都是顺序执行的,run方法每次启动都会停留1秒,1秒内都没有消息则退出
- ThreadMode.ASYNC:直接丢到线程池中执行,与ThreadMode.BACKGROUND相比,都是在非主线程上接收消息,但是BACKGROUND是顺序执行,而ASYNC则是异步接收消息
- invokeSubscriber:通过反射来回调接收事件的方法
- mainThreadPoster:实现类是HandlerPoster,继承自Handler,实现了Poster接口,注入了主线程的Looper,也就是该消息是在主线程上运行的
- backgroundPoster: 实现类是BackgroundPoster,继承自Runnable,实现了Poster接口,消息是在线程池中单个线程里顺序执行的
- asyncPoster:实现类是AsyncPoster,继承自Runnable,实现了Poster接口,消息是在线程池中异步执行的
HandlerPoster.java:
public class HandlerPoster extends Handler implements Poster {
private final PendingPostQueue queue;
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
}
- PendingPostQueue:消息队列,消息类是PendingPost,通过单链表实现
- PendingPost:消息类,用于封装当前消息的事件以及订阅者,通过PendingPost.obtainPendingPost返回一个消息对象,obtainPendingPost先从List缓存池中获取,没有才new一个对象
- maxMillisInsideHandleMessage的值是10
- 先判断有没有消息,如果没有消息则退出循环
- 如果有消息,但是消息接收的方法执行时间超过maxMillisInsideHandleMessage,也就是10毫秒,则重新发送消息并退出循环
BackgroundPoster.java:
final class BackgroundPoster implements Runnable, Poster {
private final PendingPostQueue queue;
private final EventBus eventBus;
private volatile boolean executorRunning;
BackgroundPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
eventBus.getExecutorService().execute(this);
}
}
}
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
}
- 每次只启动一个线程池里的线程,并且最长停留1秒,如果1秒内有消息则循环处理,没有则结束任务
AsyncPost.java:
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 = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
- 不管有多少消息都扔到线程池里异步执行
关于线程池:
public class EventBus{
private final ExecutorService executorService;
EventBus(EventBusBuilder builder) {
executorService = builder.executorService;
}
}
public class EventBusBuilder{
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
}
public class Executors {
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
}
- 从代码上可以看出EventBus创建的线程是CachedThreadPool,它的特点是,核心线程数为0,最大线程数是Integer.MAX_VALUE,最大等待时间60秒,队列使用的是SynchronousQueue
- 也就是说所有的任务都是异步立即执行的,没有等待时间
最后我们分析一下是如何取消注册订阅者的:
EventBus.getDefault().unregister(this);
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());
}
}
- 首先typesBySubscriber通过订阅者找到该订阅者订阅的所有事件,然后循环调用unsubscribeByEventType方法
- 然后将当前订阅者从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--;
}
}
}
}
- 在这个方法里就是subscriptionsByEventType通过事件找到所有订阅了该事件的订阅者,然后循环遍历找出要取消注册的那个订阅者并删除
所以总结下来取消订阅的过程就是将该订阅者,以及它下面订阅的所有事件从typesBySubscriber、subscriptionsByEventType这两个map中对应数据删除