EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序内各组件间、组件与后台线程间的通信。
作为一个消息总线主要有三个组成部分:
事件(Event):可以是任意类型的对象。通过事件的发布者将事件进行传递。
事件订阅者(Subscriber):接收特定的事件。
事件发布者(Publisher):用于通知 Subscriber 有事件发生。可以在任意线程任意位置发送事件。

上图解释了整个EventBus的大概工作流程:事件的发布者(Publisher)将事件(Event)通过post()方法发送。EventBus内部进行处理,找到订阅了该事件(Event)的事件订阅者(Subscriber)。然后该事件的订阅者(Subscriber)通过onEvent()方法接收事件进行相关处理(关于onEvent()在EventBus 3.0中有改动,下面详细说明)。
二、EventBus的简单使用
1、把EventBus依赖到项目
build.gradle添加引用
1
| compile 'de.greenrobot:eventbus:3.0.0-beta1'
|
2、构造事件(Event)对象。也就是发送消息类
每一个消息类,对应一种事件。这里我们定义两个消息发送类。后面讲解具体作用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class NewsEvent { private String message; public NewsEvent(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class ToastEvent { private String content; public ToastEvent(String content) { this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
|
3、注册/解除事件订阅(Subscriber)
1
| EventBus.getDefault().register(this);
|
具体注册了对什么事件的订阅,这个需要onEvent()方法来说明。在EventBus 3.0之前,onEvent()方法是用来接收指定事件(Event)类型对象,然后进行相关处理操作。在EventBus 3.0之后,onEvent()方法可以自定义方法名,不过要加入注解@Subscribe。
1 2 3 4
| @Subscribe public void onToastEvent(ToastEvent event){ Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show(); }
|
通过register(this)来表示该订阅者进行了订阅,通过onToastEvent(ToastEvent event)表示指定对事件ToastEvent的订阅。到这里订阅就完成了。
需要注意的是:一般在onCreate()方法中进行注册订阅。在onDestory()方法中进行解除订阅。
1 2 3 4 5
| @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }
|
4 、发送消息
订阅已经完成,那么便可以发送订阅了。
1
| EventBus.getDefault().post(new ToastEvent("Toast,发个提示,祝大家新年快乐!"));
|
那么onToastEvent(ToastEvent event)会收到事件,并弹出提示。
EventBus的基础使用流程就是这样的。
其实,EventBus还有好多其他的功能。下面我们一个个介绍。
三、EventBus的进阶使用
1.线程模式ThreadMode
当你接收的的事件后,如果处于非UI线程,你要更新UI怎么办?如果处于UI线程,你要进行耗时操作,怎么办?等等其他情况,通过ThreadMode统统帮你解决。
用法展示:
1 2 3 4 5
| @Subscribe(threadMode = ThreadMode.MainThread) public void onNewsEvent(NewsEvent event){ String message = event.getMessage(); mTv_message.setText(message); }
|
使用起来很简单,通过@Subscribe(threadMode = ThreadMode.MainThread)
即可指定。
下面具体介绍下ThreadMode。
关于ThreadMode,一共有四种模式PostThread,PostThread,BackgroundThread以及Async。
PostThread:事件的处理在和事件的发送在相同的进程,所以事件处理时间不应太长,不然影响事件的发送线程。
MainThread: 事件的处理会在UI线程中执行。事件处理时间不能太长,这个不用说的,长了会ANR的。
BackgroundThread:如果事件是在UI线程中发布出来的,那么事件处理就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么事件处理直接在该子线程中执行。所有待处理事件会被加到一个队列中,由对应线程依次处理这些事件,如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。
Async:事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,每个事件会开启一个线程。
2.priority事件优先级
事件的优先级类似广播的优先级,优先级越高优先获得消息。
用法展示:
1 2 3 4
| @Subscribe(priority = 100) public void onToastEvent(ToastEvent event){ Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show(); }
|
当多个订阅者(Subscriber)对同一种事件类型进行订阅时,即对应的事件处理方法中接收的事件类型一致,则优先级高(priority 设置的值越大),则会先接收事件进行处理;优先级低(priority 设置的值越小),则会后接收事件进行处理。
除此之外,EventBus也可以终止对事件继续传递的功能。
用法展示:
1 2 3 4 5
| @Subscribe(priority = 100) public void onToastEvent(ToastEvent event){ Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show(); EventBus.getDefault().cancelEventDelivery(event); }
|
这样其他优先级比100低,并且订阅了该事件的订阅者就会接收不到该事件。
3.EventBus黏性事件
EventBus除了普通事件也支持粘性事件。可以理解成:订阅在发布事件之后,但同样可以收到事件。订阅/解除订阅和普通事件一样,但是处理订阅的方法有所不同,需要注解中添加sticky = true。
用法展示:
1 2 3 4 5
| @Subscribe(priority = 100,sticky = true) public void onToastEvent(ToastEvent event){ Toast.makeText(MainActivity.this,event.getContent(),Toast.LENGTH_SHORT).show(); EventBus.getDefault().cancelEventDelivery(event); }
|
这样,假设一个ToastEvent 的事件已经发布,此时还没有注册订阅。当设置了sticky = true,在ToastEvent 的事件发布后,进行注册。依然能够接收到之前发布的事件。
不过这个时候,发布事件的方式就改变了。
1
| EventBus.getDefault().postSticky(new ToastEvent("Toast,发个提示,祝大家新年快乐!"));
|
我们如果不再需要该粘性事件我们可以移除
1
| EventBus.getDefault().removeStickyEvent(ToastEvent.class);
|
或者调用移除所有粘性事件
1
| EventBus.getDefault().removeAllStickyEvents();
|
4.EventBus配置
EventBus在2.3版本中添加了EventBuilder去配置EventBus的各方各面。
比如:如何去构建一个在发布事件时没有订阅者时保持沉默的EventBus。
1 2 3 4
| EventBus eventBus = EventBus.builder() .logNoSubscriberMessages(false) .sendNoSubscriberEvent(false) .build();
|
通过上述设置,当一个事件没有订阅者时,不会输出log信息,也不会发布一条默认信息。
配置默认的EventBus实例,使用EventBus.getDefault()是一个简单的方法。获取一个单例的EventBus实例。EventBusBuilder也允许使用installDefaultEventBus方法去配置默认的EventBus实例。
注意:不同的EventBus 的对象的数据是不共享的。通过一个EventBus 对象去发布事件,只有通过同一个EventBus 对象订阅事件,才能接收该事件。所以以上使用EventBus.getDefault()获得的都是同一个实例。
四、原理
EventBus
实现了观察者模式,使用方法非常简单
下面文章主要讲解EventBus的实现原理。
EventBus内部有一个map,当register时往map中增加一个元素(key为事件的类型,value为观察者),post时根据事件类型找到观察者之后,对其反射调用。
下面我们从register方法开始:
1 2 3 4 5 6 7 8 9 10
| public void register(Object object) { Multimap, EventHandler> methodsInListener = finder.findAllHandlers(object); handlersByTypeLock.writeLock().lock(); try { handlersByType.putAll(methodsInListener); } finally { handlersByTypeLock.writeLock().unlock(); } }
|
调用eventBus.register(new Event())时,会将事件类型及观察者(封装为EventHandler)放置在SetMultimap, EventHandler> handlersByType中,这是一个线程安全的对象容器,卸载事件也是在这个容器中做移除操作。根据事件类型查找观察者时使用了策略模式,HandlerFindingStrategy finder做为策略接口,目前只有一个策略实现AnnotatedHandlerFinder(查找带有Subscribe注解的方法)。
有了这样一个map,调用post时只需要根据类型找到观察者就行了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public void post(Object event) { Set> dispatchTypes = flattenHierarchy(event.getClass()); boolean dispatched = false; for (Class eventType : dispatchTypes) { handlersByTypeLock.readLock().lock(); try { Set wrappers = handlersByType.get(eventType); if (!wrappers.isEmpty()) { dispatched = true; for (EventHandler wrapper : wrappers) { enqueueEvent(event, wrapper); } } } finally { handlersByTypeLock.readLock().unlock(); } } if (!dispatched && !(event instanceof DeadEvent)) { post(new DeadEvent(this, event)); } dispatchQueuedEvents(); }
|
这里查找到参数匹配的EventHandler
后并没有立刻执行反射调用,而是分发到了事件队列(ThreadLocal> eventsToDispatch)
中,当所有事件分发完毕之后,事件队列做统一的事件消费。
下面是一些EventBus源码解析。
getDefault()
1 2 3 4 5 6 7 8 9 10 11
| static volatile EventBus defaultInstance; public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }
|
通过上述代码可以得知,getDefault()中通过双检查锁(DCL)机制实现了EventBus的单例机制,获得了一个默认配置的EventBus对象。
下面我们继续看register()方法。
register()
在了解register()之前,我们先要了解一下EventBus中的几个关键的成员变量。方便对下面内容的理解。
1 2 3 4 5 6 7 8
| private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; private final Map<Object, List<Class<?>>> typesBySubscriber; private final Map<Class<?>, Object> stickyEvents;
|
下面看具体的register()中执行的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13
| public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); boolean forceReflection = subscriberClass.isAnonymousClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass, forceReflection); for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } }
|
由此可见,register()第一步获取订阅者的类类型. 第二步,通过SubscriberMethodFinder类来解析订阅者类,获取所有的响应函数集合. 第三步,遍历订阅函数,执行 subscribe()方法,更新订阅相关信息。
关于 subscriberMethodFinder这里就不介绍了。先跟着线索,继续看subscribe()方法。
subscribe 函数分三步。
第一步:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| Class<?> eventType = subscriberMethod.eventType; CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); Subscription newSubscription = new Subscription(subscriber, subscriberMethod); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<Subscription>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } synchronized (subscriptions) { 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; } } }
|
第二步:
1 2 3 4 5 6 7 8 9
| List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<Class<?>>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType);
|
第三步:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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); } }
|
由此可见,第一步:通过subscriptionsByEventType得到该事件类型所有订阅者信息队列,根据优先级将当前订阅者信息插入到订阅者队列subscriptionsByEventType中;
第二步:在typesBySubscriber中得到当前订阅者订阅的所有事件队列,将此事件保存到队列typesBySubscriber中,用于后续取消订阅;
第三步:检查这个事件是否是 Sticky 事件,如果是则从stickyEvents事件保存队列中取出该事件类型最后一个事件发送给当前订阅者。
到此,便完成了订阅功能。下面是订阅的具体流程图:

unregister()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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 { Log.e("EventBus", "Subscriber to unregister was not registered before: " + subscriber.getClass()); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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 --; } } } }
|
unregister()方法比较简单,主要完成了subscriptionsByEventType以及typesBySubscriber两个集合的同步。
post()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (!postingState.isPosting) { postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); 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; } } }
|
post 函数会首先得到当前线程的 post 信息PostingThreadState,其中包含事件队列,将当前事件添加到其事件队列中,然后循环调用 postSingleEvent 函数发布队列中的每个事件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| private void postSingleEvent(Object event, PostingThreadState postingState) { 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); } .................................... }
|
调用 postSingleEventForEventType 函数发布每个事件到每个订阅者。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| 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; }
|
调用 postToSubscription 函数向每个订阅者发布事件。
postToSubscription 函数中会判断订阅者的 ThreadMode,从而决定在什么 Mode 下执行事件响应函数。这里就不贴源码了。后续还牵着到反射以及线程调度问题,这里就不展开了。
以上就是post的流程,下面是具体的post的流程图。
