EventBus 源码解析
一. 简介
EventBus是适用于Android和Java的开源库,使用发布者/订阅者模式进行松散耦合。EventBus使中央通信只需几行代码即可解耦类,简化组件之间的通信,从而简化了代码,消除了依赖关系并加快了应用程序的开发。
对于Android的使用,EventBus通过解耦发布者和订阅者简化事件传递;
EventBus可以代替Android传统的Intent,Handler,Broadcast,或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法等。
特点:代码简洁,是一种发布订阅设计模式(观察者设计模式)。
EventBus库的git官方地址。
二.使用
2.1 gradle依赖
android gradle依赖eventbus库
implementation 'org.greenrobot:eventbus:3.1.1'
2.2 定义事件
用户自定义一个事件类
public static class MessageEvent { /* Additional fields if needed */ }
2.3 注册、解绑事件
我们需要Activity或者Fragment里订阅事件时,首先要先对EventBus进行注册,同时要跟随Activity或者Fragment的生命周期方法,适时地对EventBus进行解除注册。
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
2.4 处理事件
声明订阅者的订阅方法,进行处理事件,我们对处理事件的方法名字可以随便取用,但是必须要添加@Subscribe注解,同时可以指定一个具体处理该事件的线程模型。
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
2.5 发送事件
EventBus进行post发送事件可分为“普通事件”和 “粘性事件”,二者区别如下:
- 普通事件,发送事件后,只有已经订阅过的事件才能收到,后续再进行订阅该事件就收不到该事件;
- 粘性事件,发送事件后,再订阅该事件也能收到该事件;
/**
*发送普通事件
*/
EventBus.getDefault().post(new MessageEvent());
/**
*发送粘性事件
*/
EventBus.getDefault().postSticky(new MessageEvent());
三.源码解析
3.1 注册订阅过程
在EventBus的使用中,我们要想Activity或者Fragment进行订阅处理事件,则先要进行注册成为事件的订阅者。即执行如下操作:
EventBus.getDefault().register(context)
注册可以分为两个过程:创建EventBus对象、 注册成为订阅者。
3.1.1 创建EventBus 对象
我们跟进 EventBus的getDefault()方法源码看到,这是一个静态方法,通过Double-Check实现单例模式,返回了一个EventBus对象
/**
* Convenience singleton for apps using a process-wide EventBus instance.
*/
public static EventBus getDefault() {
EventBus instance = defaultInstance;
if (instance == null) {
synchronized (EventBus.class) {
instance = EventBus.defaultInstance;
if (instance == null) {
instance = EventBus.defaultInstance = new EventBus();
}
}
}
return instance;
}
在实例化EventBus过程中调用new EventBus()的this(DEFAULT_BUILDER)方法完成,实际是在构造方法EventBus(builder)中使用build构造者模式进行赋值和初始化EventBus对象。
/**
* Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
* central bus, consider {@link #getDefault()}.
*/
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
上述通过以DEFAULT_BUILDER对象为参数,调用this(DEFAULT_BUILDER)方法,从而创建EventBus实例并赋值,具体参数含义以及用途我们后续进行讲解。
其中 DEFAULT_BUILDER 是EventBus的final类型的成员变量。
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
EventBusBuilder 类的部分源码如下,可以发现上述EventBus对象在创建的时候使用了EventBusBuilder的成员变量来配置参数信息。
/**
* Creates EventBus instances with custom parameters and also allows to install a custom default EventBus instance.
* Create a new builder using {@link EventBus#builder()}.
*/
public class EventBusBuilder {
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
boolean logSubscriberExceptions = true;
boolean logNoSubscriberMessages = true;
boolean sendSubscriberExceptionEvent = true;
boolean sendNoSubscriberEvent = true;
boolean throwSubscriberException;
boolean eventInheritance = true;
boolean ignoreGeneratedIndex;
boolean strictMethodVerification;
ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
List<Class<?>> skipMethodVerificationForClasses;
List<SubscriberInfoIndex> subscriberInfoIndexes;
Logger logger;
MainThreadSupport mainThreadSupport;
EventBusBuilder() {
}
}
上述为EventBus创建实例的过程。
3.1.2 注册成为订阅者
拿到Event的实例后,我们接着跟进register方法的源码:
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
上述函数,先通过反射方法拿到订阅者Object的Class对象subscriberClass,然后调用subscriberMethodFinder.findSubscriberMethods(subscriberClass),拿到订阅者subscriberClass对象的所有订阅方法SubscriberMetho的集合。最后遍历集合,调用subscribe(subscriber, subscriberMethod),完成订阅者对所有方法的订阅。
其中subscriberMethodFinder对象是在上述EventBus的构造方法中完成了实例化,这里不再进行详述;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
然后我们就查看findSubscriberMethods方法,将Class对象作为参数,通过反射等方法来获取到该Class下所有的Subscribe方法的集合,源码如下:
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
private static final int POOL_SIZE = 4;
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//METHOD_CACHE 以Class为key,订阅方法的集合为value
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
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;
}
}
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
//prepareFindState方法获取FindState 的实例
FindState findState = prepareFindState();
//初始化findState的subscriberClass
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//通过反射获取到subscriberClass 订阅的方法
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//prepareFindState方法获取FindState 的实例
FindState findState = prepareFindState();
//初始化findState的subscriberClass
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 {
//通过反射获取到subscriberClass 订阅的方法
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new 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();
///判断方法的参数是否为1
if (parameterTypes.length == 1) {
//查找Subscribe注解
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");
}
}
}
/**
* 通过findState返回 findState的订阅方法的集合,释放清空findState,并添加到FIND_STATE_POOL缓存数组中
* @param findState
* @return
*/
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
总结以上代码:反射拿到订阅者的class对象,subscriberMethodFinder通过他拿到所有订阅方法SubscriberMetho的集合。再通过遍历集合,调用subscribe(subscriber, subscriberMethod),完成订阅者对所有方法的订阅。
终于,我们要进行分析subscribe(subscriber, subscriberMethod)方法,如下:
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//获取订阅方法的事件类型class
Class<?> eventType = subscriberMethod.eventType;
//对订阅者subscriber和订阅方法进行封装成 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//获取事件类型,所对应的订阅者事件集合
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//subscriptions 非空判断
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;
}
}
//获取订阅者subscriber所订阅的订阅 事件类型集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
//将该事件类型添加到事件类型集合subscribedEvents中
subscribedEvents.add(eventType);
//事件是否为粘性事件
if (subscriberMethod.sticky) {
//是否考虑eventType所有子类的现有粘性事件,默认为true
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();
// 判断candidateEventType是否是eventType的子类
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
//检查是否是粘性事件,发布到订阅
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
//检查是否是粘性事件,发布到订阅
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
在上面subscribe订阅事件的方法,若事件是粘性事件,则会执行checkPostStickyEventToSubscription方法,跟进去看到源码如下:
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
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, isMainThread());
}
}
checkPostStickyEventToSubscription方法内部最终调用的是postToSubscription方法;在后续我们会讲到Post方法,其实Post方法发送事件最终也是调用到postToSubscription;由此可知,订阅粘性事件的其实好比发送了一个post,所以粘性事件在发送后注册也能收到。
3.2 取消订阅过程
取消订阅的方法:EventBus.getDefault().unregister(this),跟进去unregister方法如下:
/**
* 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());
}
}
unregister方法,先通过typesBySubscriber 拿到当前解绑的订阅者所对应的订阅的事件类型集合subscribedTypes ;
若subscribedTypes 为null,则打印“要解绑的订阅者之前并没有进行注册”的相关日志warning信息;
若subscribedTypes 非null,遍历该事件类型集合,对每个事件类型执行unsubscribeByEventType(subscriber, eventType)方法,遍历结束后将该订阅者从typesBySubscriber的Map中remove掉。接下来我们跟进去unsubscribeByEventType的源码,如下:
/**
* Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber.
*/
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
从上述unsubscribeByEventType方法中,我们看到先调用subscriptionsByEventType的get方法,获得eventType事件类型,所对应的订阅者事件集合;然后对订阅者事件集合进行遍历操作,将当前订阅者的订阅事件移除掉。
至此,unregister 取消订阅过程就分析完毕了。
3.3 post发送事件
EventBus.getDefault().post(new MessageEvent()); 点进去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 = 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;
}
}
}
currentPostingThreadState 是一个本地线程内部存储类ThreadLocal
//ThreadLocal 是一个线程内部的存储类,可以在指定线程内存储数据,数据存储以后,只有指定线程可以得到存储的数据
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
Post方法中, 先从currentPostingThreadState 中get拿到了postingState 对象,然后将event事件添加到postingState的事件队列中;因为postingState.isPosting初始为false,所以进入if语句里面,标记当前线程是不是主线程,并标记postingState.isPosting为true;然后在while (!eventQueue.isEmpty())循环中,从事件队列头部取出事件,调用postSingleEvent方法发送事件,最后在finally代码块里面重置postingState的isPosting 和
isMainThread 状态;
下面来看postSingleEvent方法,如下:
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);
}
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));
}
}
}
首先拿到订阅事件event的class对象 eventClass , eventInheritance 默认为true,调用lookupAllEventTypes(eventClass)方法拿到eventClass所对应的所有父类集合的对象的eventTypes ,然后遍历eventTypes 对象,最终调用postSingleEventForEventType方法进行发送事件;跟进postSingleEventForEventType方法如下:
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;
}
先调用subscriptionsByEventType的get方法,获取到当前事件类型对应的订阅者事件集合,然后对订阅者事件集合进行判断遍历,最后调用postToSubscription方法,即上面分析的粘性事件最后调用到的方法;
因此可以发现,post事件发送的重点就是在postToSubscription方法之中,点击去看源码,如下:
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);
}
}
在方法中首先对订阅者事件标注的线程进行判断,以MAIN线程为例:若订阅者事件标注的线程为MAIN,就表明订阅者事件方法体想要在UI线程中执行,这个时候会判断当前线程是不是主线程,如果是主线程就直接调用invokeSubscriber方法进行操作,如果不是主线程,则通过mainThreadPoster进行线程切换;
当前为主线程方法下的invokeSubscriber方法如下:
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);
}
}
invokeSubscriber方法是通过反射的invoke来实现。
当前线程不为主线程时候,通过mainThreadPoster.enqueue(subscription, event)来实现线程切换;
其中mainThreadPoster是HandlerPoster的实例对象,mainThreadPoster调用enqueue方法
将订阅者事件和event对象加入队列操作;
HandlerPoster继承了Handler,同时也实现了Poster接口; 其中HandlerPoster的handleMessage方法,该方法运行在主线程,查看其enqueue和 handleMessage方法如下:
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
handleMessage种调用到了eventBus的invokeSubscriber方法,而invokeSubscriber又调用到invokeSubscriber方法。同样还是通过反射来实现方法调用。
四.重点总结
4.1 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;
}
1.ThreadMode 线程模式
ThreadMode.POSTING,默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高。
ThreadMode.MAIN,如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
ThreadMode.MAIN_ORDERED,无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
ThreadMode.BACKGROUND,如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件。
ThreadMode.ASYNC,无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。
2.是否粘性事件
3.事件优先级
4.2 构造方法重要参数
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
三个Map
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
三个线程调度Poster
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);