以下分析都是基于EventBus 3.x
一、简介
EventBus,Android和Java的发布/订阅事件总线,用于简化组件之间的通信方式。
在我们传统的写法中,Activity之间的通信使用Intent,Service跟Activity之间使用广播broadcast,Fragment和Activity之间会相互持有对方的引用, 这类方式的问题在于:通信方式没有实现解耦,一旦我们的组件发生
了变化,对应的通信方式就需要跟着修改,因此为了较大限度地解耦,可以考虑使用EventBus,他在一定程度上,可以代替Handle、Intent、Brodcast等实现。
二、使用
1、引入
在build.gradle文件增加以下配置即可:
implementation 'org.greenrobot:eventbus:3.1.1'
2、混淆配置
需要在你的 proguard-rules.pro 混淆配置文件里面增加以下配置,具体的可以看看官方的ProGuard配置规则
-keepattributes *Annotation*
-keepclassmembers class * {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
3、使用
1)、定义事件类型
public class StringMessageEvent {
private String msg;
private String action;
public String getMsg() {
return msg;
}
public String getAction() {
return action;
}
public StringMessageEvent(String msg, String action) {
this.msg = msg;
this.action = action;
}
}
2)、注册
public class EventBusDemoActivity extends BaseActivity {
private static final String TAG = Thread.currentThread().getStackTrace()[1].getClassName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
3)、发布事件
@Override
protected void onItemClick() {
EventBus.getDefault().post(new StringMessageEvent("发射", "跳转"));
}
4)、定义监听者
@Subscribe(threadMode = ThreadMode.POSTING)
public void onMessageEventPostThread(StringMessageEvent event) {
Log.e( "event PostThread", "消息: " + event + " thread: " + Thread.currentThread().getName() );
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEventMainThread(StringMessageEvent event) {
Log.e( "event MainThread", "消息: " + event + " thread: " + Thread.currentThread().getName());
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEventBackgroundThread(StringMessageEvent event) {
Log.e( "event BackgroundThread", "消息: " + event + " thread: " + Thread.currentThread().getName());
}
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessageEventAsync(StringMessageEvent event) {
Log.e( "event Async", "消息: " + event + " thread: " + Thread.currentThread().getName());
}
线程类型
在定义监听处理方法的时候,需要添加Subscribe注解,EventBus才能够识别,并且可以指定执行方法在哪个线程运行,其中的线程类型threadMode一共有四种:
a)、ThreadMode.POSTING:消息在哪个线程发送,就在哪个线程执行;
b)、ThreadMode.MAIN:主线程执行;
c)、ThreadMode.BACKGROUND:BACKGROUND线程执行;
d)、ThreadMode.ASYNC:异步线程执行;
5)、运行结果
com.ccg.watchersdemo E/event MainThread: 消息: 发射 thread: main
com.ccg.watchersdemo E/event PostThread: 消息: 发射 thread: main
com.ccg.watchersdemo E/event Async: 消息: 发射 thread: pool-1-thread-1
com.ccg.watchersdemo E/event BackgroundThread: 消息: 发射 thread: pool-1-thread-2
可以看到,在点击进行消息发送之后,监听者都接收到了相关信息。
源码分析
在使用上就是这么简单。看了上面的栗子之后,我们不禁有这样子的疑问:EventBus在传递消息的过程中,跟我们平常维护一个list注册一个listener来实现监听通知有啥差别;如果是遍历通知的方式,里面有没有啥提高性能的实现?其4种线程执行模型又有什么不同,我们在使用的过程中,又该怎样决定使用哪种模式呢?
注册流程register分析
以上面例子为例,在我们调用EventBus.getDefault().register(this);注册的时候,
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
EventBus 会先获取 this 也就是 EventBusDemoActivity 对应的类,调用SubscriberMethodFinder对象的findSubscriberMethods方法:
这个方法返回的是SubscriberMethod的list数组,其实现首先从 METHOD_CACHE (Map,key是监听类对象,如EventBusDemoActivity,value是List,也即是EventBusDemoActivity所有的监听方法) 里面寻找注册者是否曾经注册过,如果有的话,直接从缓存里面获取即可。
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) { //即使生成了索引(默认值:false),也强制使用反射,不配置默认为false
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;
}
}
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);
}
因为ignoreGeneratedIndex 不配置的话,默认为false,所以我们直接看到findUsingInfo的实现。因为FinsState在初始化的时候,其subscriberInfo也为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");
}
}
}
findUsingReflectionInSingleClass会首先获取EventBusDemoActivity的所有方法,遍历方法列表,看是否有注解定义,如果有的话,通过 method.getParameterTypes() 获取其方法参数,创建一个SubscriberMethod对象,存储监听者的相关信息,放在list列表里面,在遍历完成时,返回过滤到的列表,以EventBusDemoActivity为key,list为value放进METHOD_CACHE 这个map里面。并将遍历完生成的list 返回。在上面的例子中,返回的就是:
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
重新看回register方法,在得到list之后遍历列表,
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);
}
}
}
以订阅类型(如string、int、long等,在上面的例子中,就是StringMessageEvent)为key,创建list对象作为value(Subscription里面有两个成员,一个记录监听者EventBusDemoActivity,一个记录监听者里面的监听方法onMessageEventAsync),存进 subscriptionsByEventType 里面,同时会根据优先级subscriberMethod.priority的大小进行排序。然后循环执行,遍历结束之后,以StringMessageEvent为key 对应的value(list),一共就会4条数据。
至此,注册的流程就结束了。
通知流程post分析
post 通知的流程就比较简单了,当我们调用EventBus.getDefault().post(new StringMessageEvent(“发射”, “跳转”)) 执行post操作的时候,根据 post 要发送的对象的类型作为key,在subscriptionsByEventType 找到所有的监听者列表,根据监听者要执行的线程类型不同,放在对应的AsyncPoster、BackgroundPoster、HandlerPoster、subscription.subscriberMethod.method.invoke队列或者直接执行invoke进行通知(动态代理)。
至此,post的流程就结束了。
小结
整个流程,只要我们理解了EventBus里面的以下几个重要的成员变量即能较好地掌握整个实现。
//发送类型为key,对应的事件及其父类为value,如上面的例子,key是StringMessageEvent,value是StringMessageEvent和Object(所有对象的父类)。起提高性能作用,不用每次都遍历。
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
//key是监听类对象,如EventBusDemoActivity,value是List<SubscriberMethod>,也即是 EventBusDemoActivity所有的监听方法***
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
//key:EventBusDemoActivity value:对应的监听列表,
private final Map<Object, List<Class<?>>> typesBySubscriber;