EventBus 使用方法及源码分析
EventBus 使用方法及源码分析
标签(空格分隔): android
#基本使用方法
**订阅模式**
POSTING:发布跟订阅在同一线程,开销最小,默认的模式;
MAIN:
如果发布者在非ui线程,订阅者会切换到ui线程;
MAIN_ORDERED:
订阅者会先放到队列里,直到执行完相关逻辑代码才会处理订阅的代码。如果发布者在非ui线程,订阅者会切换到ui线程;
BACKGROUND
如果发布者在ui线程,订阅者会另开一个线程;如果发布者在非ui线程,订阅者会在当前线程;
ASYNC
订阅者都会另开一个线程
Sticky 默认为false
Sticky=true
Sticky事件只指事件消费者在事件发布之后才注册的也能接收到该事件的特殊类型。
**订阅事件**
EventBus.getDefault().register(this); // 订阅
**订阅回调方法**
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true) // sticky事件
public void hand(Event01 event01) {
String name = event01.getName();
}
**发布事件**
EventBus.getDefault().postSticky(new Event01("jack")); // 发布sticky事件
EventBus.getDefault().post(new Event01("jack")); // 发布非sticky事件
#源码分析
##订阅流程的源码分析
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
1.通过单例模式EventBus.getDefault()得到实例eventBus, 然后通过eventBus.register(Object subscriber) 方法实现订阅;
2.在register方法里, 首先会通过实例得到相应的类, 然后通过(该实例是在EventBus(EventBusBuilder builder )构造方法里实例化的)subscriberMethodFinder.findSubscriberMethods(subscriberClass) 得到订阅者的该类中所有订阅方法;
org.greenrobot.eventbus.SubscriberMethodFinder 类:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
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;
}
}
3.该方法里ConcurrentHashMap(METHOD_CACHE实现缓存)保存类的所有订阅者方法,如果缓存中没有相应的信息,ignoreGeneratedIndex(boolean默认是false)则调用findUsingInfo(subscriberClass),得到了相应的信息会保存METHOD_CACHE方便下次用;
org.greenrobot.eventbus.SubscriberMethodFinder 类:
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);
}
4.该方法里把相关信息保存在FindState实例(通过prepareFindState()该方法里通过FIND_STATE_POOL数组进行stateFind的缓存如果数组里面有stateFind则直接方法并把数组相应的位置的保存对象设为null, 否则就new一个)里面,
org.greenrobot.eventbus.SubscriberMethodFinder 类:
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())); // 保存到findState对象里
}
}
} 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");
}
}
}
5.通过findUsingReflectionInSingleClass(FindState findState)该方法里通过反射得到所有DeclaredMethod,
然后遍历所有的方法,通过判断方法的参数个数为1,然后再获取方法注解类是否为Subscribe,判断通过后stateFind.checkAdd(Method method, Class<?> eventType)添加到stateFind实例的anyMethodByEventType
hashMap里,该方法会检查是否有存在多个订阅者监听相同的事件类型,checkAdd返回true,最后会将注解类里信息保存到SubscriberMethod实例,添加到stateFind的subscriberMethods集合里面;
org.greenrobot.eventbus.SubscriberMethodFinder 类:
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;
}
6.由1-5 得到了一些订阅者的信息保存在stateFind实例里,findUsingInfo方法最后通过getMethodsAndRelease(findState)得到List,然后将stateFind实例的属性进行回收, 再将stateFind保存到FIND_STATE_POOL(步骤4有去缓存拿的操作) 数组里面方便下次再用;
7. 由1-6 eventBus.register(Object subscriber)方法得到了List<SubscriberMethod>后再遍历调用subscribe(subscriber, subscriberMethod);
org.greenrobot.eventbus.EventBus;类
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); // 同一个订阅者不能订阅2个相同的事件类型
}
}
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) { // 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);
}
}
}
8.subscribe方法对非Sticky事件总要管理2个集合,subscriptionsByEventType (Map
eventType, CopyOnWriteArrayList>)(key是事件类型,value是一个集合,Subscription实例保存subscriber订阅者,subscriberMethod订阅者里面的订阅方法), typesBySubscriber(Map
##发布事件流程的源码分析
- EventBus.getDefault().post(mainEvent); 发布一个事件类型为MainEvent的事件, post(Object event)方法如下:PostingThreadState类型的对象里面存有一个事件队列,isMainThread是否是主线程,isPosting是否发送, canceled是否已经取消发送;
org.greenrobot.eventbus.EventBus;类
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get(); // ThreadLocal保存的线程私有对象
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;
}
}
}
2.如果postingThreadState里面的事件队列(先进先出)不为空会一直循环执行postSingleEvent方法, 该方法首先lookupAllEventTypes里面通过一个集合缓存事件类型类(包括父类),得到事件类型的类然后遍历执行postSingleEventForEventType方法;
org.greenrobot.eventbus.EventBus;类
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));
}
}
}
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
3.该方法首先会通过事件类型的类去subscriptionsByEventType集合里面找到List集合(订阅事件的流程8有对该集合的保存操作),然后遍历集合将一些数据保存在线程私有的变量postingState里面,执行postToSubscription方法,我们这里订阅类型是Main, 当前执行的线程是主线程,所以执行invokeSubscriber(subscription, event);该方法是通过反射执行订阅者实例里面的订阅方法。
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;
}
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);
}
}
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);
}
}
##疑问解答
- eventBus是怎么判断主线程的?
通过Logger.AndroidLogger.isAndroidLogAvailable()得到log可用,然后通过getAndroidMainLooperOrNull方法得到Looper.getMainLooper()对象,再用该对象判断是否跟Looper.myLooper()是同一对象来得知是否是主线程。
- 用到什么数据结构?
队列 - 用到了什么模式?
单例(双重检查)模式
还没有评论,来说两句吧...