EventBus 原理解析

转:https://www.jianshu.com/p/d9516884dbd4

EventBus是一款在 Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发送者分开,简化了组件之间的通信,使用简单、效率高、体积小!下边是官方的 EventBus 原理图:

EventBus 的用法可以参考官网,这里不做过多的说明。本文主要是从 EventBus 使用的方式入手,来分析 EventBus 背后的实现原理,以下内容基于eventbus:3.1.1版本,主要包括如下几个方面的内容:

Subscribe注解

注册事件订阅方法

取消注册

发送事件

事件处理

粘性事件

Subscriber Index

核心流程梳理

一、Subscribe注解

EventBus3.0 开始用Subscribe注解配置事件订阅方法,不再使用方法名了,例如:

@SubscribepublicvoidhandleEvent(Stringevent){// do something}

其中事件类型可以是 Java 中已有的类型或者我们自定义的类型。

具体看下Subscribe注解的实现:

@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})public@interfaceSubscribe{// 指定事件订阅方法的线程模式,即在那个线程执行事件订阅方法处理事件,默认为POSTINGThreadModethreadMode()defaultThreadMode.POSTING;// 是否支持粘性事件,默认为falsebooleansticky()defaultfalse;// 指定事件订阅方法的优先级,默认为0,如果多个事件订阅方法可以接收相同事件的,则优先级高的先接收到事件intpriority()default0;}

所以在使用Subscribe注解时可以根据需求指定threadMode、sticky、priority三个属性。

其中threadMode属性有如下几个可选值:

ThreadMode.POSTING,默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高。

ThreadMode.MAIN,如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。

ThreadMode.MAIN_ORDERED,无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。

ThreadMode.BACKGROUND,如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件。

ThreadMode.ASYNC,无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。

二、注册事件订阅方法

注册事件的方式如下:

EventBus.getDefault().register(this);

其中getDefault()是一个单例方法,保证当前只有一个EventBus实例:

publicstaticEventBusgetDefault(){if(defaultInstance==null){synchronized(EventBus.class){if(defaultInstance==null){defaultInstance=newEventBus();}}}returndefaultInstance;}

继续看new EventBus()做了些什么:

publicEventBus(){this(DEFAULT_BUILDER);}

在这里又调用了EventBus的另一个构造函数来完成它相关属性的初始化:

EventBus(EventBusBuilderbuilder){logger=builder.getLogger();subscriptionsByEventType=newHashMap<>();typesBySubscriber=newHashMap<>();stickyEvents=newConcurrentHashMap<>();mainThreadSupport=builder.getMainThreadSupport();mainThreadPoster=mainThreadSupport!=null?mainThreadSupport.createPoster(this):null;backgroundPoster=newBackgroundPoster(this);asyncPoster=newAsyncPoster(this);indexCount=builder.subscriberInfoIndexes!=null?builder.subscriberInfoIndexes.size():0;subscriberMethodFinder=newSubscriberMethodFinder(builder.subscriberInfoIndexes,builder.strictMethodVerification,builder.ignoreGeneratedIndex);logSubscriberExceptions=builder.logSubscriberExceptions;logNoSubscriberMessages=builder.logNoSubscriberMessages;sendSubscriberExceptionEvent=builder.sendSubscriberExceptionEvent;sendNoSubscriberEvent=builder.sendNoSubscriberEvent;throwSubscriberException=builder.throwSubscriberException;eventInheritance=builder.eventInheritance;executorService=builder.executorService;}

DEFAULT_BUILDER就是一个默认的EventBusBuilder

privatestaticfinalEventBusBuilderDEFAULT_BUILDER=newEventBusBuilder();

如果有需要的话,我们也可以通过配置EventBusBuilder来更改EventBus的属性,例如用如下方式注册事件:

EventBus.builder().eventInheritance(false).logSubscriberExceptions(false).build().register(this);

有了EventBus的实例就可以进行注册了:

publicvoidregister(Objectsubscriber){// 得到当前要注册类的Class对象Class<?>subscriberClass=subscriber.getClass();// 根据Class查找当前类中订阅了事件的方法集合,即使用了Subscribe注解、有public修饰符、一个参数的方法// SubscriberMethod类主要封装了符合条件方法的相关信息:// Method对象、线程模式、事件类型、优先级、是否是粘性事等List<SubscriberMethod>subscriberMethods=subscriberMethodFinder.findSubscriberMethods(subscriberClass);synchronized(this){// 循环遍历订阅了事件的方法集合,以完成注册for(SubscriberMethodsubscriberMethod:subscriberMethods){subscribe(subscriber,subscriberMethod);}}}

可以看到register()方法主要分为查找和注册两部分,首先来看查找的过程,从findSubscriberMethods()开始:

List<SubscriberMethod>findSubscriberMethods(Class<?>subscriberClass){// METHOD_CACHE是一个ConcurrentHashMap,直接保存了subscriberClass和对应SubscriberMethod的集合,以提高注册效率,赋值重复查找。List<SubscriberMethod>subscriberMethods=METHOD_CACHE.get(subscriberClass);if(subscriberMethods!=null){returnsubscriberMethods;}// 由于使用了默认的EventBusBuilder,则ignoreGeneratedIndex属性默认为false,即是否忽略注解生成器if(ignoreGeneratedIndex){subscriberMethods=findUsingReflection(subscriberClass);}else{subscriberMethods=findUsingInfo(subscriberClass);}// 如果对应类中没有符合条件的方法,则抛出异常if(subscriberMethods.isEmpty()){thrownewEventBusException("Subscriber "+subscriberClass+" and its super classes have no public methods with the @Subscribe annotation");}else{// 保存查找到的订阅事件的方法METHOD_CACHE.put(subscriberClass,subscriberMethods);returnsubscriberMethods;}}

findSubscriberMethods()流程很清晰,即先从缓存中查找,如果找到则直接返回,否则去做下一步的查找过程,然后缓存查找到的集合,根据上边的注释可知findUsingInfo()方法会被调用:

privateList<SubscriberMethod>findUsingInfo(Class<?>subscriberClass){FindStatefindState=prepareFindState();findState.initForSubscriber(subscriberClass);// 初始状态下findState.clazz就是subscriberClasswhile(findState.clazz!=null){findState.subscriberInfo=getSubscriberInfo(findState);// 条件不成立if(findState.subscriberInfo!=null){SubscriberMethod[]array=findState.subscriberInfo.getSubscriberMethods();for(SubscriberMethodsubscriberMethod:array){if(findState.checkAdd(subscriberMethod.method,subscriberMethod.eventType)){findState.subscriberMethods.add(subscriberMethod);}}}else{// 通过反射查找订阅事件的方法findUsingReflectionInSingleClass(findState);}// 修改findState.clazz为subscriberClass的父类Class,即需要遍历父类findState.moveToSuperclass();}// 查找到的方法保存在了FindState实例的subscriberMethods集合中。// 使用subscriberMethods构建一个新的List<SubscriberMethod>// 释放掉findStatereturngetMethodsAndRelease(findState);}

findUsingInfo()方法会在当前要注册的类以及其父类中查找订阅事件的方法,这里出现了一个FindState类,它是SubscriberMethodFinder的内部类,用来辅助查找订阅事件的方法,具体的查找过程在findUsingReflectionInSingleClass()方法,它主要通过反射查找订阅事件的方法:

privatevoidfindUsingReflectionInSingleClass(FindStatefindState){Method[]methods;try{// This is faster than getMethods, especially when subscribers are fat classes like Activitiesmethods=findState.clazz.getDeclaredMethods();}catch(Throwableth){// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149methods=findState.clazz.getMethods();findState.skipSuperClasses=true;}// 循环遍历当前类的方法,筛选出符合条件的for(Methodmethod:methods){// 获得方法的修饰符intmodifiers=method.getModifiers();// 如果是public类型,但非abstract、static等if((modifiers&Modifier.PUBLIC)!=0&&(modifiers&MODIFIERS_IGNORE)==0){// 获得当前方法所有参数的类型Class<?>[]parameterTypes=method.getParameterTypes();// 如果当前方法只有一个参数if(parameterTypes.length==1){SubscribesubscribeAnnotation=method.getAnnotation(Subscribe.class);// 如果当前方法使用了Subscribe注解if(subscribeAnnotation!=null){// 得到该参数的类型Class<?>eventType=parameterTypes[0];// checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回trueif(findState.checkAdd(method,eventType)){// 得到Subscribe注解的threadMode属性值,即线程模式ThreadModethreadMode=subscribeAnnotation.threadMode();// 创建一个SubscriberMethod对象,并添加到subscriberMethods集合findState.subscriberMethods.add(newSubscriberMethod(method,eventType,threadMode,subscribeAnnotation.priority(),subscribeAnnotation.sticky()));}}}elseif(strictMethodVerification&&method.isAnnotationPresent(Subscribe.class)){StringmethodName=method.getDeclaringClass().getName()+"."+method.getName();thrownewEventBusException("@Subscribe method "+methodName+"must have exactly 1 parameter but has "+parameterTypes.length);}}elseif(strictMethodVerification&&method.isAnnotationPresent(Subscribe.class)){StringmethodName=method.getDeclaringClass().getName()+"."+method.getName();thrownewEventBusException(methodName+" is a illegal @Subscribe method: must be public, non-static, and non-abstract");}}}

到此register()方法中findSubscriberMethods()流程就分析完了,我们已经找到了当前注册类及其父类中订阅事件的方法的集合。接下来分析具体的注册流程,即register()中的subscribe()方法:

privatevoidsubscribe(Objectsubscriber,SubscriberMethodsubscriberMethod){// 得到当前订阅了事件的方法的参数类型Class<?>eventType=subscriberMethod.eventType;// Subscription类保存了要注册的类对象以及当前的subscriberMethodSubscriptionnewSubscription=newSubscription(subscriber,subscriberMethod);// subscriptionsByEventType是一个HashMap,保存了以eventType为key,Subscription对象集合为value的键值对// 先查找subscriptionsByEventType是否存在以当前eventType为key的值CopyOnWriteArrayList<Subscription>subscriptions=subscriptionsByEventType.get(eventType);// 如果不存在,则创建一个subscriptions,并保存到subscriptionsByEventTypeif(subscriptions==null){subscriptions=newCopyOnWriteArrayList<>();subscriptionsByEventType.put(eventType,subscriptions);}else{if(subscriptions.contains(newSubscription)){thrownewEventBusException("Subscriber "+subscriber.getClass()+" already registered to event "+eventType);}}// 添加上边创建的newSubscription对象到subscriptions中intsize=subscriptions.size();for(inti=0;i<=size;i++){if(i==size||subscriberMethod.priority>subscriptions.get(i).subscriberMethod.priority){subscriptions.add(i,newSubscription);break;}}// typesBySubscribere也是一个HashMap,保存了以当前要注册类的对象为key,注册类中订阅事件的方法的参数类型的集合为value的键值对// 查找是否存在对应的参数类型集合List<Class<?>>subscribedEvents=typesBySubscriber.get(subscriber);// 不存在则创建一个subscribedEvents,并保存到typesBySubscriberif(subscribedEvents==null){subscribedEvents=newArrayList<>();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)){ObjectstickyEvent=entry.getValue();checkPostStickyEventToSubscription(newSubscription,stickyEvent);}}}else{ObjectstickyEvent=stickyEvents.get(eventType);checkPostStickyEventToSubscription(newSubscription,stickyEvent);}}}

这就是注册的核心流程,所以subscribe()方法主要是得到了subscriptionsByEventType、typesBySubscriber两个 HashMap。我们在发送事件的时候要用到subscriptionsByEventType,完成事件的处理。当取消 EventBus 注册的时候要用到typesBySubscriber、subscriptionsByEventType,完成相关资源的释放。

三、取消注册

接下来看,EventBus 如何取消注册:

EventBus.getDefault().unregister(this);

核心的方法就是unregister():

publicsynchronizedvoidunregister(Objectsubscriber){// 得到当前注册类对象 对应的 订阅事件方法的参数类型 的集合List<Class<?>>subscribedTypes=typesBySubscriber.get(subscriber);if(subscribedTypes!=null){// 遍历参数类型集合,释放之前缓存的当前类中的Subscriptionfor(Class<?>eventType:subscribedTypes){unsubscribeByEventType(subscriber,eventType);}// 删除以subscriber为key的键值对typesBySubscriber.remove(subscriber);}else{logger.log(Level.WARNING,"Subscriber to unregister was not registered before: "+subscriber.getClass());}}

内容很简单,继续看unsubscribeByEventType()方法:

privatevoidunsubscribeByEventType(Objectsubscriber,Class<?>eventType){// 得到当前参数类型对应的Subscription集合List<Subscription>subscriptions=subscriptionsByEventType.get(eventType);if(subscriptions!=null){intsize=subscriptions.size();// 遍历Subscription集合for(inti=0;i<size;i++){Subscriptionsubscription=subscriptions.get(i);// 如果当前subscription对象对应的注册类对象 和 要取消注册的注册类对象相同,则删除当前subscription对象if(subscription.subscriber==subscriber){subscription.active=false;subscriptions.remove(i);i--;size--;}}}}

所以在unregister()方法中,释放了typesBySubscriber、subscriptionsByEventType中缓存的资源。

四、发送事件

当发送一个事件的时候,我们可以通过如下方式:

EventBus.getDefault().post("Hello World!")

可以看到,发送事件就是通过post()方法完成的:

publicvoidpost(Objectevent){// currentPostingThreadState是一个PostingThreadState类型的ThreadLocal// PostingThreadState类保存了事件队列和线程模式等信息PostingThreadStatepostingState=currentPostingThreadState.get();List<Object>eventQueue=postingState.eventQueue;// 将要发送的事件添加到事件队列eventQueue.add(event);// isPosting默认为falseif(!postingState.isPosting){// 是否为主线程postingState.isMainThread=isMainThread();postingState.isPosting=true;if(postingState.canceled){thrownewEventBusException("Internal error. Abort state was not reset");}try{// 遍历事件队列while(!eventQueue.isEmpty()){// 发送单个事件// eventQueue.remove(0),从事件队列移除事件postSingleEvent(eventQueue.remove(0),postingState);}}finally{postingState.isPosting=false;postingState.isMainThread=false;}}}

所以post()方法先将发送的事件保存的事件队列,然后通过循环出队列,将事件交给postSingleEvent()方法处理:

privatevoidpostSingleEvent(Objectevent,PostingThreadStatepostingState)throwsError{Class<?>eventClass=event.getClass();booleansubscriptionFound=false;// eventInheritance默认为true,表示是否向上查找事件的父类if(eventInheritance){// 查找当前事件类型的Class,连同当前事件类型的Class保存到集合List<Class<?>>eventTypes=lookupAllEventTypes(eventClass);intcountTypes=eventTypes.size();// 遍历Class集合,继续处理事件for(inth=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(newNoSubscriberEvent(this,event));}}}

postSingleEvent()方法中,根据eventInheritance属性,决定是否向上遍历事件的父类型,然后用postSingleEventForEventType()方法进一步处理事件:

privatebooleanpostSingleEventForEventType(Objectevent,PostingThreadStatepostingState,Class<?>eventClass){CopyOnWriteArrayList<Subscription>subscriptions;synchronized(this){// 获取事件类型对应的Subscription集合subscriptions=subscriptionsByEventType.get(eventClass);}// 如果已订阅了对应类型的事件if(subscriptions!=null&&!subscriptions.isEmpty()){for(Subscriptionsubscription:subscriptions){// 记录事件postingState.event=event;// 记录对应的subscriptionpostingState.subscription=subscription;booleanaborted=false;try{// 最终的事件处理postToSubscription(subscription,event,postingState.isMainThread);aborted=postingState.canceled;}finally{postingState.event=null;postingState.subscription=null;postingState.canceled=false;}if(aborted){break;}}returntrue;}returnfalse;}

postSingleEventForEventType()方法核心就是遍历发送的事件类型对应的Subscription集合,然后调用postToSubscription()方法处理事件。

五、处理事件

接着上边的继续分析,postToSubscription()内部会根据订阅事件方法的线程模式,间接或直接的以发送的事件为参数,通过反射执行订阅事件的方法。

privatevoidpostToSubscription(Subscriptionsubscription,Objectevent,booleanisMainThread){// 判断订阅事件方法的线程模式switch(subscription.subscriberMethod.threadMode){// 默认的线程模式,在那个线程发送事件就在那个线程处理事件casePOSTING:invokeSubscriber(subscription,event);break;// 在主线程处理事件caseMAIN:// 如果在主线程发送事件,则直接在主线程通过反射处理事件if(isMainThread){invokeSubscriber(subscription,event);}else{// 如果是在子线程发送事件,则将事件入队列,通过Handler切换到主线程执行处理事件// mainThreadPoster 不为空mainThreadPoster.enqueue(subscription,event);}break;// 无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。// mainThreadPoster 不为空caseMAIN_ORDERED:if(mainThreadPoster!=null){mainThreadPoster.enqueue(subscription,event);}else{invokeSubscriber(subscription,event);}break;caseBACKGROUND:// 如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件if(isMainThread){backgroundPoster.enqueue(subscription,event);}else{// 如果在子线程发送事件,则直接在发送事件的线程通过反射处理事件invokeSubscriber(subscription,event);}break;// 无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。caseASYNC:asyncPoster.enqueue(subscription,event);break;default:thrownewIllegalStateException("Unknown thread mode: "+subscription.subscriberMethod.threadMode);}}

可以看到,postToSubscription()方法就是根据订阅事件方法的线程模式、以及发送事件的线程来判断如何处理事件,至于处理方式主要有两种:

一种是在相应线程直接通过invokeSubscriber()方法,用反射来执行订阅事件的方法,这样发送出去的事件就被订阅者接收并做相应处理了:

voidinvokeSubscriber(Subscriptionsubscription,Objectevent){try{subscription.subscriberMethod.method.invoke(subscription.subscriber,event);}catch(InvocationTargetExceptione){handleSubscriberException(subscription,event,e.getCause());}catch(IllegalAccessExceptione){thrownewIllegalStateException("Unexpected exception",e);}}

另外一种是先将事件入队列(其实底层是一个List),然后做进一步处理,我们以mainThreadPoster.enqueue(subscription, event)为例简单的分析下,其中mainThreadPoster是HandlerPoster类的一个实例,来看该类的主要实现:

publicclassHandlerPosterextendsHandlerimplementsPoster{privatefinalPendingPostQueuequeue;privatebooleanhandlerActive;......publicvoidenqueue(Subscriptionsubscription,Objectevent){// 用subscription和event封装一个PendingPost对象PendingPostpendingPost=PendingPost.obtainPendingPost(subscription,event);synchronized(this){// 入队列queue.enqueue(pendingPost);if(!handlerActive){handlerActive=true;// 发送开始处理事件的消息,handleMessage()方法将被执行,完成从子线程到主线程的切换if(!sendMessage(obtainMessage())){thrownewEventBusException("Could not send handler message");}}}}@OverridepublicvoidhandleMessage(Messagemsg){booleanrescheduled=false;try{longstarted=SystemClock.uptimeMillis();// 死循环遍历队列while(true){// 出队列PendingPostpendingPost=queue.poll();......// 进一步处理pendingPosteventBus.invokeSubscriber(pendingPost);......}}finally{handlerActive=rescheduled;}}}

所以HandlerPoster的enqueue()方法主要就是将subscription、event对象封装成一个PendingPost对象,然后保存到队列里,之后通过Handler切换到主线程,在handleMessage()方法将中将PendingPost对象循环出队列,交给invokeSubscriber()方法进一步处理:

voidinvokeSubscriber(PendingPostpendingPost){Objectevent=pendingPost.event;Subscriptionsubscription=pendingPost.subscription;// 释放pendingPost引用的资源PendingPost.releasePendingPost(pendingPost);if(subscription.active){// 用反射来执行订阅事件的方法invokeSubscriber(subscription,event);}}

这个方法很简单,主要就是从pendingPost中取出之前保存的event、subscription,然后用反射来执行订阅事件的方法,又回到了第一种处理方式。所以mainThreadPoster.enqueue(subscription, event)的核心就是先将将事件入队列,然后通过Handler从子线程切换到主线程中去处理事件。

backgroundPoster.enqueue()和asyncPoster.enqueue也类似,内部都是先将事件入队列,然后再出队列,但是会通过线程池去进一步处理事件。

六、粘性事件

一般情况,我们使用 EventBus 都是准备好订阅事件的方法,然后注册事件,最后在发送事件,即要先有事件的接收者。但粘性事件却恰恰相反,我们可以先发送事件,后续再准备订阅事件的方法、注册事件。

由于这种差异,我们分析粘性事件原理时,先从事件发送开始,发送一个粘性事件通过如下方式:

EventBus.getDefault().postSticky("Hello World!");

来看postSticky()方法是如何实现的:

publicvoidpostSticky(Objectevent){synchronized(stickyEvents){stickyEvents.put(event.getClass(),event);}post(event);}

postSticky()方法主要做了两件事,先将事件类型和对应事件保存到stickyEvents中,方便后续使用;然后执行post(event)继续发送事件,这个post()方法就是之前发送的post()方法。所以,如果在发送粘性事件前,已经有了对应类型事件的订阅者,及时它是非粘性的,依然可以接收到发送出的粘性事件。

发送完粘性事件后,再准备订阅粘性事件的方法,并完成注册。核心的注册事件流程还是我们之前的register()方法中的subscribe()方法,前边分析subscribe()方法时,有一段没有分析的代码,就是用来处理粘性事件的:

privatevoidsubscribe(Objectsubscriber,SubscriberMethodsubscriberMethod){..................// 如果当前订阅事件的方法的Subscribe注解的sticky属性为true,即该方法可接受粘性事件if(subscriberMethod.sticky){// 默认为true,表示是否向上查找事件的父类if(eventInheritance){// stickyEvents就是发送粘性事件时,保存了事件类型和对应事件Set<Map.Entry<Class<?>,Object>>entries=stickyEvents.entrySet();for(Map.Entry<Class<?>,Object>entry:entries){Class<?>candidateEventType=entry.getKey();// 如果candidateEventType是eventType的子类或if(eventType.isAssignableFrom(candidateEventType)){// 获得对应的事件ObjectstickyEvent=entry.getValue();// 处理粘性事件checkPostStickyEventToSubscription(newSubscription,stickyEvent);}}}else{ObjectstickyEvent=stickyEvents.get(eventType);checkPostStickyEventToSubscription(newSubscription,stickyEvent);}}}

可以看到,处理粘性事件就是在 EventBus 注册时,遍历stickyEvents,如果当前要注册的事件订阅方法是粘性的,并且该方法接收的事件类型和stickyEvents中某个事件类型相同或者是其父类,则取出stickyEvents中对应事件类型的具体事件,做进一步处理。继续看checkPostStickyEventToSubscription()处理方法:

privatevoidcheckPostStickyEventToSubscription(SubscriptionnewSubscription,ObjectstickyEvent){if(stickyEvent!=null){postToSubscription(newSubscription,stickyEvent,isMainThread());}}

最终还是通过postToSubscription()方法完成粘性事件的处理,这就是粘性事件的整个处理流程。

七、Subscriber Index

回顾之前分析的 EventBus 注册事件流程,主要是在项目运行时通过反射来查找订事件的方法信息,这也是默认的实现,如果项目中有大量的订阅事件的方法,必然会对项目运行时的性能产生影响。其实除了在项目运行时通过反射查找订阅事件的方法信息,EventBus 还提供了在项目编译时通过注解处理器查找订阅事件方法信息的方式,生成一个辅助的索引类来保存这些信息,这个索引类就是Subscriber Index,其实和ButterKnife的原理类似。

要在项目编译时查找订阅事件的方法信息,首先要在 app 的 build.gradle 中加入如下配置:

android{defaultConfig{javaCompileOptions{annotationProcessorOptions{// 根据项目实际情况,指定辅助索引类的名称和包名arguments=[eventBusIndex:'com.shh.sometest.MyEventBusIndex']}}}}dependencies{compile'org.greenrobot:eventbus:3.1.1'// 引入注解处理器annotationProcessor'org.greenrobot:eventbus-annotation-processor:3.1.1'}

然后在项目的 Application 中添加如下配置,以生成一个默认的 EventBus 单例:

EventBus.builder().addIndex(newMyEventBusIndex()).installDefaultEventBus();

之后的用法就和我们平时使用 EventBus 一样了。当项目编译时会在生成对应的MyEventBusIndex类:

MyEventBusIndex

对应的源码如下:

publicclassMyEventBusIndeximplementsSubscriberInfoIndex{privatestaticfinalMap<Class<?>,SubscriberInfo>SUBSCRIBER_INDEX;static{SUBSCRIBER_INDEX=newHashMap<Class<?>,SubscriberInfo>();putIndex(newSimpleSubscriberInfo(MainActivity.class,true,newSubscriberMethodInfo[]{newSubscriberMethodInfo("changeText",String.class),}));}privatestaticvoidputIndex(SubscriberInfoinfo){SUBSCRIBER_INDEX.put(info.getSubscriberClass(),info);}@OverridepublicSubscriberInfogetSubscriberInfo(Class<?>subscriberClass){SubscriberInfoinfo=SUBSCRIBER_INDEX.get(subscriberClass);if(info!=null){returninfo;}else{returnnull;}}}

其中SUBSCRIBER_INDEX是一个HashMap,保存了当前注册类的 Class 类型和其中事件订阅方法的信息。

接下来分析下使用 Subscriber Index 时 EventBus 的注册流程,我们先分析:

EventBus.builder().addIndex(newMyEventBusIndex()).installDefaultEventBus();

首先创建一个EventBusBuilder,然后通过addIndex()方法添加索引类的实例:

publicEventBusBuilderaddIndex(SubscriberInfoIndexindex){if(subscriberInfoIndexes==null){subscriberInfoIndexes=newArrayList<>();}subscriberInfoIndexes.add(index);returnthis;}

即把生成的索引类的实例保存在subscriberInfoIndexes集合中,然后用installDefaultEventBus()创建默认的 EventBus实例:

publicEventBusinstallDefaultEventBus(){synchronized(EventBus.class){if(EventBus.defaultInstance!=null){thrownewEventBusException("Default instance already exists."+" It may be only set once before it's used the first time to ensure consistent behavior.");}EventBus.defaultInstance=build();returnEventBus.defaultInstance;}}

publicEventBusbuild(){// this 代表当前EventBusBuilder对象returnnewEventBus(this);}

即用当前EventBusBuilder对象创建一个 EventBus 实例,这样我们通过EventBusBuilder配置的 Subscriber Index 也就传递到了EventBus实例中,然后赋值给EventBus的defaultInstance成员变量。之前我们在分析 EventBus 的getDefault()方法时已经见到了defaultInstance:

publicstaticEventBusgetDefault(){if(defaultInstance==null){synchronized(EventBus.class){if(defaultInstance==null){defaultInstance=newEventBus();}}}returndefaultInstance;}

所以在 Application 中生成了 EventBus 的默认单例,这样就保证了在项目其它地方执行EventBus.getDefault()就能得到唯一的 EventBus 实例!之前在分析注册流程时有一个

方法findUsingInfo():

privateList<SubscriberMethod>findUsingInfo(Class<?>subscriberClass){FindStatefindState=prepareFindState();findState.initForSubscriber(subscriberClass);while(findState.clazz!=null){// 查找SubscriberInfofindState.subscriberInfo=getSubscriberInfo(findState);// 条件成立if(findState.subscriberInfo!=null){// 获得当前注册类中所有订阅了事件的方法SubscriberMethod[]array=findState.subscriberInfo.getSubscriberMethods();for(SubscriberMethodsubscriberMethod:array){// findState.checkAdd()之前已经分析过了,即是否在FindState的anyMethodByEventType已经添加过以当前eventType为key的键值对,没添加过返回trueif(findState.checkAdd(subscriberMethod.method,subscriberMethod.eventType)){// 将subscriberMethod对象添加到subscriberMethods集合findState.subscriberMethods.add(subscriberMethod);}}}else{findUsingReflectionInSingleClass(findState);}findState.moveToSuperclass();}returngetMethodsAndRelease(findState);}

由于我们现在使用了 Subscriber Index 所以不会通过findUsingReflectionInSingleClass()来反射解析订阅事件的方法。我们重点来看getSubscriberInfo()都做了些什么:

privateSubscriberInfogetSubscriberInfo(FindStatefindState){// 该条件不成立if(findState.subscriberInfo!=null&&findState.subscriberInfo.getSuperSubscriberInfo()!=null){SubscriberInfosuperclassInfo=findState.subscriberInfo.getSuperSubscriberInfo();if(findState.clazz==superclassInfo.getSubscriberClass()){returnsuperclassInfo;}}// 该条件成立if(subscriberInfoIndexes!=null){// 遍历索引类实例集合for(SubscriberInfoIndexindex:subscriberInfoIndexes){// 根据注册类的 Class 类查找SubscriberInfoSubscriberInfoinfo=index.getSubscriberInfo(findState.clazz);if(info!=null){returninfo;}}}returnnull;}

subscriberInfoIndexes就是在前边addIndex()方法中创建的,保存了项目中的索引类实例,即MyEventBusIndex的实例,继续看索引类的getSubscriberInfo()方法,来到了MyEventBusIndex类中:

@OverridepublicSubscriberInfogetSubscriberInfo(Class<?>subscriberClass){SubscriberInfo info=SUBSCRIBER_INDEX.get(subscriberClass);if(info!=null){returninfo;}else{returnnull;}}

即根据注册类的 Class 类型从SUBSCRIBER_INDEX查找对应的SubscriberInfo,如果我们在注册类中定义了订阅事件的方法,则info不为空,进而上边findUsingInfo()方法中findState.subscriberInfo != null成立,到这里主要的内容就分析完了,其它的和之前的注册流程一样。

所以 Subscriber Index 的核心就是项目编译时使用注解处理器生成保存事件订阅方法信息的索引类,然后项目运行时将索引类实例设置到 EventBus 中,这样当注册 EventBus 时,从索引类取出当前注册类对应的事件订阅方法信息,以完成最终的注册,避免了运行时反射处理的过程,所以在性能上会有质的提高。项目中可以根据实际的需求决定是否使用 Subscriber Index。

八、小结

结合上边的分析,我们可以总结出register、post、unregister的核心流程:

register

post

unregister

到这里 EventBus 几个重要的流程就分析完了,整体的设计思路还是值得我们学习的。和 Android 自带的广播相比,使用简单、同时又兼顾了性能。但如果在项目中滥用的话,各种逻辑交叉在一起,也可能会给后期的维护带来困难。

作者:SheHuan

链接:https://www.jianshu.com/p/d9516884dbd4

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271