EventBus的作用与用途网上很多,这里就不多做概述。为了不成为一个知其然不知所以然的人,找了段时间,阅读了EventBus的源码,下面做下简单的介绍:
EventBus的控制器是EventBus类,subscriber首先需要在EventBus上register:
private synchronized void register(Object subscriber, boolean sticky, int priority) {
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
在这里,主要是findSubscriberMethods方法,它通过subscriber的反射,找到它需要回调的函数,是以onEvent..开头的:
private static final String ON_EVENT_METHOD_NAME = "onEvent";
这些函数至少要有一个参数,而且第一个参数必须是事件类型,这样才能通过事件类型找到订阅者:
String methodKey = methodKeyBuilder.toString();
if (eventTypesFound.add(methodKey)) {
// Only add if not already found in a sub class
subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));
}
通过注册就在EventBus上有了一个事件类型-订阅者的映射关系也就是map,在这里要说下,这个表可能不是最新的,因为:
synchronized (methodCache) {
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
return subscriberMethods;
}
而且有了注册就必须unRegister,否则会报错。
最后讲讲EventBus是怎么Post的:
/** 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 = 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的时候在哪个线程,比如UI线程,如果 是UI线程的话OnEventMainThread就会执行,OnEventThread也会执行,如果不是的话,OnEventMainThread就不会执行,OnEventThread会执行,另外两种类型是跟OnEventMainThread同样的道 理,看是否属于需要。