EventBus之源码解析

时间:2021-06-14 17:15:54

参考文档

Android EventBus源码解析 带你深入理解EventBus : http://blog.csdn.net/lmj623565791/article/details/40920453

1. 概念

EventBus是Android下高效的发布/订阅事件总线机制。作用是可以代替传统的Intent,Handler,Broadcast或接口函数在Fragment,Activity,Service,线程之间传递数据,执行方法。特点是代码简洁,是一种发布订阅设计模式(Publish/Subsribe),或称作观察者设计模式。
EventBus的内部实质上是调用了反射机制 , 在下面会进行详细讲解.

2. 下载地址

Github网址 : https://github.com/greenrobot/EventBus
Gradle引入 :

compile 'org.greenrobot:eventbus:3.0.0'

3. EventBus使用流程图

  1. Publisher是发布者, 通过post()方法将消息事件Event发布到事件总线
  2. EventBus是事件总线, 遍历所有已经注册事件的订阅者们,找到里边的onEvent等4个方法,分发Event
  3. Subscriber是订阅者, 收到事件总线发下来的消息。即onEvent方法被执行。注意参数类型必须和发布者发布的参数一致。

EventBus之源码解析

只需要四步 :

  • 随便定义一个类 :
public class AnyEventType { /* Additional fields if needed */ }
  • 注册订阅者subscribers : 在onCreate()方法或构造函数中
eventBus.register(this);
  • 然后在订阅者中定义订阅的方法 , 总共有4个 , 根据自己的线程要求来选择
// 注解必须加上
@Subscribe
public void onEventMainThread(AnyEventType event) {/* Do something */};
@Subscribe
public void onEventPostThread(AnyEventType event) {/* Do something */};
@Subscribe
public void onEventBackgroundThread(AnyEventType event) {/* Do something */};
@Subscribe
public void onEventAsync(AnyEventType event) {/* Do something */};
  • 发布者发布消息
EventBus.getDefault().post(event);

具体的使用方法不多说了 , 大家可以参考https://github.com/greenrobot/EventBus

4. 结构分析

看下面这段代码 , 这里是订阅者的一个案例

public class SampleComponent extends Fragment 
{


@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}

public void onEventMainThread(param) { }

public void onEventPostThread(param) { }

public void onEventBackgroundThread(param) { }

public void onEventAsync(param) { }

@Override
public void onDestroy()
{
super.onDestroy();
EventBus.getDefault().unregister(this);
}

}

大多数情况下 , 都会在onCreate中进行register,在onDestory中进行unregister ;
其中 , register(this)就是去当前类,遍历所有的方法,找到onEvent开头的然后进行存储 , 而onEvent后面可以写四种,也就是上面出现的四个方法,决定了当前的方法最终在什么线程运行,怎么运行.

那么 , 既然注册了 , 就需要调用

EventBus.getDefault().post(param);  

调用很简单,发布信息,只要把这个param发布出去,EventBus会在它内部存储的方法中,进行扫描,找到参数匹配的,就使用反射进行调用。
因为在注册时 , EventBus就在内部存储了一堆onEvent开头的方法,然后post的时候,根据post传入的参数,去找到匹配的方法,反射调用。
那么,EventBus的内部是如何进行存储的呢 ? 其实EventBus内部使用了Map进行存储,键就是参数的Class类型。

5. 进入EventBus的源码机制

(1) 首先 , 从注册者开始

EventBus.getDefault().register(this);

我们来看看EventBus.getDefault()是如何获取EventBus实例的

    public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

这是一个典型的单例模式 , 并进行了双重判断和加锁 , 解决线程安全问题. 然后看register(this)方法

    public void register(Object subscriber) {
// 获取注册者的Class对象
Class<?> subscriberClass = subscriber.getClass();
// 获取方法的list集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}

在register()方法里面 , 首先获取了传入过来的注册者的Class对象 , 看见Class对象 , 第一反应应该就是跟反射机制有关吧 , 然后 , 看下subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法 , 返回一个list集合

 private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 从map集合中,根据Class的键,获取所有方法名的集合
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
// 如果这个集合不为null,说明已经获取过了,那么直接return
if (subscriberMethods != null) {
return subscriberMethods;
}
// 获取方法名集合
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
// 如果方法名集合还是为null,抛出异常
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
// 将Class和方法名以键值对的形式存储到map集合中
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}

从上面的代码中分析可得 , 注册者的类名和其相应的方法名是以键值对的形式存储在了一个map集合中了 , 那么我们再来看看它是如何获取相应的方法名集合subscriberMethods 的

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}

看findUsingReflectionInSingleClass(findState)方法

    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");
}
}
}

关键的部分来了 , 第21行 , 将method, threadMode, eventType传入构造了:new SubscriberMethod(method, threadMode, eventType)。添加到List,最终返回。我们再返回去看register()方法

     for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}

for循环扫描到的方法,然后去调用suscribe方法。

    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);
}
}
}

我们在上面提到了 , subscriberMethod中保存了method, threadMode, eventType等属性.
第3行 , 把我们的传入的参数封装成了一个:Subscription(subscriber, subscriberMethod);
第4-6行 , 根据subscriberMethod.eventType,去subscriptionsByEventType去查找一个CopyOnWriteArrayList ,如果没有则创建。
第7行 , 这里的subscriptionsByEventType是个Map,(key:eventType ; value:CopyOnWriteArrayList) ; 这个Map其实就是EventBus存储方法的地方,一定要记住!
第15-21行:实际上,就是添加newSubscription;并且是按照优先级添加的。可以看到,优先级越高,会插到在当前List的前面。
第23-28行:根据subscriber存储它所有的eventType ; 依然是map;key:subscriber ,value:List< eventType > ;知道就行,非核心代码,主要用于isRegister的判断。
第30-48行:判断sticky;如果为true,从stickyEvents中根据eventType去查找有没有stickyEvent,如果有则立即发布去执行。stickyEvent其实就是我们post时的参数。其中 , checkPostStickyEventToSubscription方法实质是调用了postToSubscription方法 , 我们在后面讲.

在这里register方法就讲完了 , 总结为 :

  • 扫描了所有的方法,把匹配的方法最终保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList< Subscription > )中;

  • eventType是我们方法参数的Class,Subscription中则保存着subscriber, subscriberMethod(method, threadMode, eventType ).

(2) 接下来 , 是post方法 , 发送消息
register完毕,知道了EventBus如何存储我们的方法了,下面看看post它又是如何调用我们的方法的。
再看源码之前,我们猜测下:register时,把方法存在subscriptionsByEventType;那么post肯定会去subscriptionsByEventType去取方法,然后调用。

    public void post(Object event) {
// currentPostingThreadState是一个ThreadLocal类型
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;
}
}
}

第3行 , currentPostingThreadState是一个ThreadLocal类型的,里面存储了PostingThreadState;PostingThreadState包含了一个eventQueue和一些标志位。如下 :

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};

第5行 , 把我们传入的event,保存到了当前线程中的一个变量PostingThreadState的eventQueue中。
第8行:判断当前是否是UI线程。
第14-16行:遍历队列中的所有的event,调用postSingleEvent(eventQueue.remove(0), postingState)方法。
这里大家会不会有疑问,每次post都会去调用整个队列么,那么不会造成方法多次调用么?
可以看到第7-9行,有个判断,就是防止该问题的,isPosting=true了,就不会往下走了。

接下来看postSingleEvent(eventQueue.remove(0), postingState)方法

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
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);
}
...
}

将我们的event,即post传入的实参;以及postingState传入到postSingleEvent中。
第2行:根据event的Class,去得到一个List< Class< ? >>;其实就是得到event当前对象的Class,以及父类和接口的Class类型;主要用于匹配,比如你传入Dog extends Dog,他会把Animal也装到该List中。
第9行:看到postSingleEventForEventType(event, postingState, clazz)方法 , 如下 :

    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;
}

遍历所有的Class,到subscriptionsByEventType去查找subscriptions;哈哈,熟不熟悉,还记得我们register里面把方法存哪了不?是不是就是这个Map;
第7-23行:遍历每个subscription,依次去调用postToSubscription(subscription, event, postingState.isMainThread) , 这个方法就是去反射执行方法了

好 , 重点来了 , 看postToSubscription(subscription, event, postingState.isMainThread) 这个方法

    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 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);
}
}

终于看到头了 , 前面已经说过subscription包含了所有执行需要的东西,大致有:subscriber, subscriberMethod(method, threadMode, eventType), priority;根据threadMode去判断应该在哪个线程去执行该方法;

    void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}

实质最终调用的是

subscription.subscriberMethod.method.invoke(subscription.subscriber, event);

反射调用方法 , 源码分析到这就结束了.

总结 :
register会把当前类中匹配的方法,存入一个map,而post会根据实参去map查找进行反射调用。