EventBus 的使用以及源码分析
概述
EventBus is a publish/subscribe event bus for Android and Java. 官方说明,一言蔽之。
EventBus 是一个基于发布/订阅 的一个事件总线。
能做什么?
再EventBus 出来之前,我们要实现事件的通知,数据传递,会怎么做?Handler、接口回调通知、使用观察者模式、广播以及一些特定场景下 Intent 也可以。线程之间切换呢?Handler、Rxjava 等。有了EventBus 又多了一种选择。除了简单易用之外,还有足够稳定。现在的版本是3.1.1,更新时间是18年8月(截至于2019.11月)。 EventBus-release 有i兴趣可以去看看官网的更新记录所以不必担心应用过程中会出现其他问题,如果有,99%是使用方式不对。
说明
贴一张官方的说明图
使用
添加依赖
//截至 2019/11 最新版本是3.1.1
implementation 'org.greenrobot:eventbus:3.1.1'
定义一个事件
用来传递承载的通知数据,就是一个普通的JavaBean。注意,EventBus 传递的事件类型不可以是基本数据类型,比如说 byte、int long 等。当可以是基本数据类型的包装类。Integer 等。String 也是可以的。
public class Person{
private int age;
private String name;
//get and set
...
}
定义一个事件的接受者
@Subscribe(threadMode = ThreadMode.MAIN)
public void receivePerson(Person person){
}
这里有几个点需要注意的点,看官方注释:Event handling methods must be annotated by {@link Subscribe}, must be public, return nothing (void), and have exactly one parameter (the event). 必须添加 ==Subscribe== 注解,必须以 ==public== 修饰。必须 返回 ==void==,形参必须是定义好的事件类型,且只可以有一个。
注册和反注册
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
以上代码是官方的实例代码,但是在实际实践过程中需要添加改动,防止重复注册这样 事件就会收到多次。
@Override
public void onStart() {
super.onStart();
if(!EventBus.getDefault().isRegistered())
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
发生事件
EventBus.getDefault().post(Person)
Subscribe注解说明
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.POSTING;
/**
* If true, delivers the most recent sticky event (posted with
* {@link EventBus#postSticky(Object)}) to this subscriber (if event available).
*/
boolean sticky() default false;
/** Subscriber priority to influence the order of event delivery.
* Within the same delivery thread ({@link ThreadMode}), higher priority subscribers will receive events before
* others with a lower priority. The default priority is 0. Note: the priority does *NOT* affect the order of
* delivery among subscribers with different {@link ThreadMode}s! */
int priority() default 0;
}
一个作用在方法上的元注解,其中有三个参数
- ThreadMode 指定事件接受的线程环境
- sticky 是否是粘性事件
- priority 优先级
一个一个来说
ThreadMode
Each subscriber method has a thread mode, which determines in which thread the method is to be called by EventBus.EventBus takes care of threading independently from the posting thread(每个订户方法都有一个线程模式,该模式确定EventBus在哪个线程中调用该方法EventBus独立于发帖线程处理线程)。翻译的有点拗口,为什么是 ==确定EventBus在哪个线程调用该方法呢?== 后面再说。
- POSTING
适用场景:订阅者将在发布事件的同一线程中直接调用。这是默认值。事件传递意味着开销最少,因为它完全避免了线程切换。因此,这是已知可以在很短时间内完成而无需主线程的简单任务的推荐模式。使用此模式的事件处理程序必须快速返回,以避免阻塞可能是主线程的发布线程
- MAIN
适用场景:在Android上,订阅者将在Android的主线程(UI线程)中被调用。如果发布线程是主线程,则将直接调用订阅者方法,从而阻止发布线程。否则,事件将排队等待传递(非阻塞)。使用此模式的订阅者必须快速返回以避免阻塞主线程。 如果不是在Android上,则其行为与{@link #POSTING}相同(EventBus 在Java 中也可使用,故有此一说)
- MAIN_ORDERED
在Android上,订阅者将在Android的主线程(UI线程)中被调用。与{@link #MAIN}不同的是,事件将始终排队等待发送。这样可以确保发布调用是非阻塞的
- BACKGROUND
在Android上,订阅者将在后台线程中被调用。如果发布线程不是主线程,则订阅者方法将直接在发布线程中调用。如果发布线程是主线程,则EventBus使用单个*后台线程,它将按顺序传递其所有事件。使用此模式的订户应尝试快速返回以避免阻塞后台线程。如果不是在Android上,则始终使用后台线程
- ASYNC
订户将在单独的线程中被调用。这始终独立于发布线程和主线程。发布事件永远不会等待使用此模式的订阅者方法。如果订阅者方法的执行可能要花费一些时间,例如,用于网络访问。避免同时触发大量长时间运行的异步订阅者方法,以限制并发线程的数量。 EventBus 使用线程池来有效地重用已完成的异步订阅者通知中的线程
sticky
借用其它博客的说法:何为黏性事件呢?简单讲,就是在发送事件之后再订阅该事件也能收到该事件。Android中就有这样的实例,也就是Sticky Broadcast,即粘性广播。正常情况下如果发送者发送了某个广播,而接收者在这个广播发送后才注册自己的Receiver,这时接收者便无法接收到 刚才的广播,为此Android引入了StickyBroadcast,在广播发送结束后会保存刚刚发送的广播(Intent),这样当接收者注册完 Receiver后就可以接收到刚才已经发布的广播。这就使得我们可以预先处理一些事件,让有消费者时再把这些事件投递给消费者.
EventBus也提供了这样的功能,有所不同是EventBus会存储所有的Sticky事件,如果某个事件在不需要再存储则需要手动进行移除。用户通过Sticky的形式发布事件,而消费者也需要通过Sticky的形式进行注册,当然这种注册除了可以接收 Sticky事件之外和常规的注册功能是一样的,其他类型的事件也会被正常处理。
粘性事件的接收以及发送
//接收
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void receiveSoundRecongnizedmsg(Person person) {
}
//发送
EventBus.getDefault().postSticky(Person);
priority
优先级:订户优先级,以影响事件传递的顺序。在同一传送线程({@link ThreadMode})中,优先级较高的订户将在优先级较低的其他订户之前接收事件。默认优先级为0。注意:优先级不会影响具有不同{@link ThreadMode}的订户之间发送的顺序!
源码分析
源码分析的流程
graph LR
开始注册-->发送事件
发送事件-->接收事件
接收事件-->取消注册
注册
/**
*subscriber 订阅的事件类型
*/
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
//通过订阅的事件的class 对象,获取到订阅该事件的方法集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//遍历集合,保存订阅关系(将订阅的事件和接收该事件的方法的映射关系保存的map集合中)
subscribe(subscriber, subscriberMethod);
}
}
}
//根据订阅事件找到该订阅事件的方法集合
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//从缓存中获取订阅方法的集合列表
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略构造所引,默认是false
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;
}
}
发送事件
/**
* Posts the given event to the event bus.
*/
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;
}
}
}
//发送事件
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//eventInheritance 是否是继承事件,默认是 true
if (eventInheritance) {
//查找所有Class对象,包括超类和接口
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));//移除事件,这里需要注意一下,是一个循环调用,如果找不到事件的订阅者,就自己发布
}
}
}
//发送事件的核心逻辑
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;
}
事件的接收
//发送的最后一步
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);
}
}
事件的优先级处理
事件优先级的处理其实就相当于插队,看代码:
// must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//获取订阅事件的类型
Class<?> eventType = subscriberMethod.eventType;
Log.d("sjy", "eventType=" + eventType.getName());
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
Log.d("sjy", "save event map");
} 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);
}
}
}
粘性事件处理
先看下粘性事件的发送
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
post(event);
}
看代码,很简单,只是将粘性事件给存起来,然后调用了普通的post 函数。在postSticky方法里,是有把事件缓存到stickyEvents中的。postSticky里的post方法,是订阅者的订阅事件的动作发生在粘性事件发布之前,此时粘性事件相当于普通事件,所以直接调用post处理即可。但如果订阅者的订阅事件的动作发生在粘性事件发布之后呢?此时就轮到stickyEvents起作用了,在注册方法里,会取出所有未处理的缓存的粘性事件,发送到checkPostStickyEventToSubscription处理,这样不就达到粘性事件的处理效果。看下代码处理:
// must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
....
//判断是否是粘性事件
if (subscriberMethod.sticky) {
//该值默认是false
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);
}
}
}
取消注册
取消注册
EventBus.getDefault().unregister(this);
/**
* Unregisters the given subscriber from all event classes.
*/
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());
}
}
没什么好说的。直接看代码就好了!!!
网友评论