您的位置:首页 > 移动开发 > Android开发

android 开源工具 EventBus的使用和源码分析

2014-08-23 11:10 881 查看
由于公司之前的技术分享,与eventbus和otto相关,因此主要参考了网上的文章,本文以下内容主要参考angeldeviljy 大神的http://www.cnblogs.com/angeldevil/p/3715934.html 文章,特此对其表示感谢. 如若不同意引用和转载,还请劳烦大神联系我,我好做相应处理!

----------------做一枚健康的码农--------------

EventBus

eventbus 使用greenrobot 提供的用来简化组件间通信的开源项目 github地址为: https://github.com/greenrobot/EventBus 它主要采用的是观察者模式(也称之为 发布者/订阅者模式), 网上另一个比较出名的square出的otto,otto在github上同样也放出了开源地址,在这里就不再添加了.两者的区别和对比在eventbus的官网上也做了表格. 个人认为最主要的是以下三点: 1: eventbus是基于命名的,而otto则是通过注释注入的方式 2:eventbus提供了线程间的事件处理 3;eventbus支持stickyEvent(当然,一般用不上=_=)

eventbus 作为消息总线,总共有三个元素:

Event:事件 Subscriber:事件订阅者,接收特定的事件 Publisher:事件发布者,用于通知Subscriber有事件发生

Event

event 可以是任何object 类型的对象

Subscriber

在EventBus中,使用约定来指定事件订阅者以简化使用。即所有事件订阅都都是以onEvent开头的函数,具体来说,函数的名字是onEvent,onEventMainThread,onEventBackgroundThread,onEventAsync这四个,这个和ThreadMode有关,后面再说。

Publisher

可以在任意线程任意位置发送事件,直接调用EventBus的`post(Object)`方法,可以自己实例化EventBus对象,但一般使用默认的单例就好了:EventBus.getDefault()`,根据post函数参数的类型,会自动调用订阅相应类型事件的函数。

ThreadMode

前面说了,Subscriber函数的名字只能是那4个,因为每个事件订阅函数都是和一个`ThreadMode`相关联的,ThreadMode指定了会调用的函数。有以下四个ThreadMode:

PostThread:事件的处理在和事件的发送在相同的进程,所以事件处理时间不应太长,不然影响事件的发送线程,而这个线程可能是UI线程。对应的函数名是onEvent。

MainThread: 事件的处理会在UI线程中执行。事件处理时间不能太长,这个不用说的,长了会ANR的,对应的函数名是onEventMainThread。

BackgroundThread:事件的处理会在一个后台线程中执行,对应的函数名是onEventBackgroundThread,虽然名字是BackgroundThread,事件处理是在后台线程,但事件处理时间还是不应该太长,因为如果发送事件的线程是后台线程,会直接执行事件,如果当前线程是UI线程,事件会被加到一个队列中,由一个线程依次处理这些事件,如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。

Async:事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,每个事件会开启一个线程(有线程池),但最好限制线程的数目。

根据事件订阅都函数名称的不同,会使用不同的ThreadMode,比如果在后台线程加载了数据想在UI线程显示,订阅者只需把函数命名为onEventMainThread。

EventBus的使用(demo以及分析在文章最后)

1 定义事件类型:
`public class MyEvent {}`

2 定义事件处理方法:`public void onEventMainThread`

3 注册订阅者:
`EventBus.getDefault().register(this)`

4 发送事件:
`EventBus.getDefault().post(new MyEvent())

EventBus的源码分析

在具体分析源码之前,先熟悉一下几个eventbus.java中几个参数,有助于理解源码(如果想理解源码,请务必区分一下几个概念)

EventType:onEvent函数中的参数,表示事件的类型

Subscriber:订阅者,即调用register注册的对象,这个对象内包含onEvent\*函数

SubscribMethod:`Subscriber`内某一特定的onEvent\*方法,内部成员包含一个`Method`类型的method成员表示这个onEvent\*方法,一个`ThreadMode`成员threadMode表示事件的处理线程,一个`Class<?>`类型的eventType成员表示事件的类型`EventType`。

Subscription,表示一个订阅对象,包含订阅源`Subscriber`,订阅源中的某一特定方法`SubscribMethod`,这个订阅的优先级`priopity`

eventBus.java中其余的几个重要成员变量

// EventType -> List<Subscription>,事件到订阅之间的映射  //这里用了CopyOnWriteArrayList ,为何这么做呢?需要留意下
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

// Subscriber -> List<EventType>,订阅者到它订阅的的所有事件类型的映射
private final Map<Object, List<Class<?>>> typesBySubscriber;

// stickEvent事件,后面会看到
private final Map<Class<?>, Object> stickyEvents;

// EventType -> List<? extends EventType>,事件到它的父事件列表的映射。即缓存一个类的所有父类
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<Class<?>, List<Class<?>>>();


注册Register

eventBus提供了多种注册事件的方式,但官方推荐使用EventBus.getDefault().register 来注册,其余的方法都已标记了Deprecated(当然在下面代码分析demo中我会介绍一下其他方法)

/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
//默认的单例模式
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}


在register中

public void register(Object subscriber) {
//官方推荐使用此方法,这样默认订阅者就是默认的四个
register(subscriber, DEFAULT_METHOD_NAME, false, 0);
}

public void register(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, false, priority);
}

@Deprecated
public void register(Object subscriber, String methodName) {
//也可以这样注册,添加订阅这的方法名,但已经飞起了
register(subscriber, methodName, false, 0);
}

public void registerSticky(Object subscriber) {
register(subscriber, DEFAULT_METHOD_NAME, true, 0);
}

public void registerSticky(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, true, priority);
}
//


以上提供的register中都会调用下面的private方法

/**
*
* @param subscriber 订阅者
* @param methodName 订阅者方法明,一般为默认
* @param sticky  //是否为粘性事件,一般为false,如果使用,一般要调用 registerSticky 方法
* @param priority   事件的优先级,一般为默认 0
*/
private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {
//这里的重点 1: findSubsrciberMethods 方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
methodName);
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//这里的重点 2: 生成订阅
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}


在 findSubscriberMethods 方法中:

private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC;
//方法缓存,这样不需要每次都去透过反射获取方法
private static final Map<String, List<SubscriberMethod>> methodCache = new HashMap<String, List<SubscriberMethod>>();

private static final Map<Class<?>, Class<?>> skipMethodVerificationForClasses = new ConcurrentHashMap<Class<?>, Class<?>>();

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {
String key = subscriberClass.getName() + '.' + eventMethodName;
List<SubscriberMethod> subscriberMethods;
synchronized (methodCache) {
//优先读取缓存
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
//有缓存,则直接返回,这样的话,就不用每次使用时都去通过下面的反射方法查找
return subscriberMethods;
}
subscriberMethods = new ArrayList<SubscriberMethod>();
Class<?> clazz = subscriberClass;
HashSet<String> eventTypesFound = new HashSet<String>();
StringBuilder methodKeyBuilder = new StringBuilder();
while (clazz != null) {
String name = clazz.getName();
if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
// Skip system classes, this just degrades performance
//过滤掉系统的类
break;
}

// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
//获取订阅这的所有方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith(eventMethodName)) {
//只找以 eventMethodName 开头的方法
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//只找public 的方法 不接受 final ,static 的修饰符的方法
Class<?>[] parameterTypes = method.getParameterTypes();
// 获取方法中的参数,也就是event--object
if (parameterTypes.length == 1) {
//  ==1 说明 订阅者的方法,参数只能有一个,就是event
// 获取 onEvent(或者你本人注册时加入的方法)后面的内容,来判断ThreadMode 4种
String modifierString = methodName.substring(eventMethodName.length());
ThreadMode threadMode;
if (modifierString.length() == 0) {
//所以,如果不是按照onevent写法的话,默认的事件处理都是postThread,这点需要注意
threadMode = ThreadMode.PostThread;
} else if (modifierString.equals("MainThread")) {
threadMode = ThreadMode.MainThread;
} else if (modifierString.equals("BackgroundThread")) {
threadMode = ThreadMode.BackgroundThread;
} else if (modifierString.equals("Async")) {
threadMode = ThreadMode.Async;
} else {
if (skipMethodVerificationForClasses.containsKey(clazz)) {
continue;
} else {
throw new EventBusException("Illegal onEvent method, check for typos: " + method);
}
}
Class<?> eventType = parameterTypes[0];//获取event的类型
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(methodName);
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
if (eventTypesFound.add(methodKey)) {
// Only add if not already found in a sub class
//封装一个订阅者方法的对象,包括 method,threadmode,eventType
subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));
}
}
} else if (!skipMethodVerificationForClasses.containsKey(clazz)) {
Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "."
+ methodName);
}
}
}

//再继续查找基类
clazz = clazz.getSuperclass();
//所有事件处理方法**必需是`public void`类型**的,并且只有一个参数表示*EventType*。
//findSubscriberMethods`不只查找*Subscriber*内的事件处理方法,**同时还会查到它的继承体系中的所有基类中的事件处理方法**

}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "
+ eventMethodName);
} else {
synchronized (methodCache) {
//存入到缓存
methodCache.put(key, subscriberMethods);
}
return subscriberMethods;
}
}


`SubscriberMethodFinder`类的作用是在Subscriber中找到所有以methodName(即默认的onEvent 当然如果你不用官方推荐的方法注册,找的就是你传入的方法名)开头的方法,每个找到的方法被表示为一个`SubscriberMethod`对象。

`SubscriberMethodFinder有两点需要知道:

所有事件处理方法**必需是`public void`类型**的,并且只有一个参数表示*EventType*。

`findSubscriberMethods`不只查找*Subscriber*内的事件处理方法,**同时还会查到它的继承体系中的所有基类中的事件处理方法*

找到*Subscriber*中的所有事件处理方法后,会对每个找到的方法(表示为`SubscriberMethod`对象)调用`subscribe`方法注册。

// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
subscribed = true;
Class<?> eventType = subscriberMethod.eventType; //获取订阅事件类型
//根据订阅事件,找出所有订阅该事件的订阅(包括订阅者,订阅方法),生成订阅列表,也属于缓存
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//生成一个新的订阅
Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
//如果没有订阅列表,这创建,并添加新的订阅,此处订阅列表并不需要根据优先级来排序
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
for (Subscription subscription : subscriptions) {
//否则判断新的订阅是否已经加入订阅列表了
if (subscription.equals(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
}

// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true);

int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
//根据优先级,来插入订阅
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
subscriptions.add(i, newSubscription);
break;
}
}

List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
//将这个订阅事件放到订阅者的订阅列表中去
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);

if (sticky) {
//如果是粘性订阅的话,直接发送上一个保存的事件(如果存在的话)
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
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, Looper.getMainLooper() == Looper.myLooper());
}
}

// 根据`SubscriberMethod`中的*EventType*类型将`Subscribtion`对象存放在`subscriptionsByEventType`中。
//        建立*EventType*到*Subscription*的映射,每个事件可以有多个订阅者。
// 根据`Subscriber`将`EventType`存放在`typesBySubscriber`中,建立*Subscriber*到*EventType*的映射,
//        每个Subscriber可以订阅多个事件。
// 如果是*Sticky*类型的订阅者,直接向它发送上个保存的事件(如果有的话)。

//        通过*Subscriber*到*EventType*的映射,我们就可以很方便地使一个Subscriber取消接收事件,
//        通过*EventType*到*Sucscribtion*的映射,可以方便地将相应的事件发送到它的每一个订阅者。

}


`subscribe`方法干了三件事:

根据`SubscriberMethod`中的*EventType*类型将`Subscribtion`对象存放在`subscriptionsByEventType`中。建立*EventType*到*Subscription*的映射,每个事件可以有多个订阅者。

根据`Subscriber`将`EventType`存放在`typesBySubscriber`中,建立*Subscriber*到*EventType*的映射,每个Subscriber可以订阅多个事件。

如果是*Sticky*类型的订阅者,直接向它发送上个保存的事件(如果有的话)。

通过*Subscriber*到*EventType*的映射(这个刚才有提到过),我们就可以很方便地使一个Subscriber取消接收事件,通过*EventType*到*Sucscribtion*的映射(这个刚才也有提到过),可以方便地将相应的事件发送到它的每一个订阅者。

这样这个注册的流程就结束了

Post

直接调用`EventBus.getDefault().post(Event)就可以发送事件,根据Event的类型就可以发送到相应事件的订阅者。

/** Posts the given event to the event bus. */
public void post(Object event) {
//获取threadLocal 这里是个ThreadLocal 要值得注意哦
PostingThreadState postingState = currentPostingThreadState.get();
//将事件添加到队列中
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);

if (postingState.isPosting) {
return;
} else {
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内使用了`PostingThreadState`的对象,并且是`ThreadLocal`,来看`PostingThreadState`的定义:

final static class PostingThreadState {
List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}


主要是有个成员`eventQueue`,由于是ThreadLocal,所以结果就是,每个线程有一个`PostingThreadState`对象,这个对象内部有一个事件的队列,并且有一个成员`isPosting`表示现在是否正在派发事件,当发送事件开始时,会依次取出队列中的事件发送出去,如果正在派发事件,那么post直接把事件加入队列后返回,还有个成员`isMainThread`,这个成员在实际派发事件时会用到,在`postSingleEvent`中会用到。

{
//根据event 获取 class
Class<? extends Object> eventClass = event.getClass();
// 根据刚才获取的class 获取 类的对象,借口以及父类等
List<Class<?>> eventTypes = findEventTypes(eventClass);
boolean subscriptionFound = false;
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//找到订阅事件对应的订阅 ,(之前在register中添加的)
subscriptions = subscriptionsByEventType.get(clazz);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
//向所有订阅改事件的订阅这发送消息( 如果有个事件订阅了 object 类型,那么就应该接受到了所有的消息)
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
subscriptionFound = true;
}
}
if (!subscriptionFound) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}


这里值得注意的是,如果一个订阅者订阅了object类型的事件,那么他就会接收到相应ThreadMode的所有事件,同样,如果订阅了父类,也会接受子类的事件

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case PostThread:
//如果是post,则在本线程中调用
invokeSubscriber(subscription, event);
break;
case MainThread:
if (isMainThread) {
//如果目前是主线程,则直接调用
invokeSubscriber(subscription, event);
} else {
//如果目前不是主线程,这放到主线程的handler中处理
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
if (isMainThread) {
//如果目前是主线程,则放runnable 线程池中
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);
}
}


上面的代码说明了: eventbus是根据订阅方法的名来确定是在哪个线程中调用的,因此如果我们没有使用官方推荐的注册方法,基本上只有在postThread中处理了

-----------我是健康的小码农---------------

`register`的函数重载中有一个可以指定订阅者的优先级,我们知道`EventBus`中有一个事件类型到List<Subscription>的映射,在这个映射中,所有的Subscription是按priority排序的,这样当post事件时,优先级高的会先得到机会处理事件。

优先级的一个应用就事,高优先级的事件处理函数可以终于事件的传递,通过`cancelEventDelivery`方法,但有一点需要注意,`这个事件的ThreadMode必须是PostThread`,并且只能终于它在处理的事件。

# 缺点

无法进程间通信,如果一个应用内有多个进程的话就没办法了

# 注意事项及要点

同一个onEvent函数不能被注册两次,所以不能在一个类中注册同时还在父类中注册

当Post一个事件时,这个事件类的父类的事件也会被Post。

Post的事件无Subscriber处理时会Post `NoSubscriberEvent`事件,当调用Subscriber失败时会Post `SubscriberExceptionEvent`事件。

Demo

可以参考原博的demo 以及我写的一个简单demo(我写的这个demo中会涉及到不使用官方推荐的注册方法,以及接受父类事件两种情况) 这两个demo以及添加了注解的源码我已经方法csdn中具体下载地址为: http://download.csdn.net/detail/zhaiwenlong/7796559

文章最后还要再次感谢 href="mailto:angeldeviljy@gmail.com" target=_blank>angeldeviljy 大神,因为他的博客才让大家能够更明白的理解eventbus,而我则是根据他的文章做了一些补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: