由于我们项目使用了EventBus2,所以查看一下源码,了解一下原理
关键的event缓存数据结构
// 订阅方法,按event类型归类
private final Map, CopyOnWriteArrayList> subscriptionsByEventType;
// 缓存已经注册的对象,可防止对象重复注册
private final Map
注册方法
private synchronized void register(ClassLoader loader, String stuckClassName, Object subscriber, String methodName, boolean sticky, int priority) {
//检查是否已经注册
if (isRegistered(subscriber)){
return;
}
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(loader, stuckClassName, subscriber.getClass(),
methodName);
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
public synchronized boolean isRegistered(Object subscriber) {
return typesBySubscriber.containsKey(subscriber);
}
查找方法
List findSubscriberMethods(ClassLoader loader, String stuckClassName, Class> subscriberClass, String eventMethodName) {
String key = subscriberClass.getName() + '.' + eventMethodName;
List subscriberMethods;
synchronized (methodCache) {
//获取之前缓存的方法,减少反射查询时间
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
return subscriberMethods;
}
subscriberMethods = new ArrayList();
Class> clazz = loadClass(loader, subscriberClass);
HashSet<String> eventTypesFound = new HashSet<String>();
StringBuilder methodKeyBuilder = new StringBuilder();
while (clazz != null) {
String name = clazz.getName();
if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
// 跳过系统方法
break;
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
//方法名字“onEvent”(默认)开头的,注册时传进来的
if (methodName.startsWith(eventMethodName)) {
int modifiers = method.getModifiers();
// 公共,非抽象和静态
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class>[] parameterTypes = method.getParameterTypes();
//只有一个参数
if (parameterTypes.length == 1) {
//截取方法名字后面的字符串
String modifierString = methodName.substring(eventMethodName.length());
@ThreadMode int threadMode;
//区分将执行的线程
if (modifierString.length() == 0) {
threadMode = ThreadMode.PostThread;
} else if (modifierString.equals("MainThread")) {
threadMode = ThreadMode.MainThread;
} else if (modifierString.equals("BackgroundThread")) {
threadMode = ThreadMode.BackgroundThread;
} else if (modifierString.equals("Async")) {
threadMode = ThreadMode.Async;
} else {
if (skipMethodVerificationForClasses.containsKey(clazz)) {
continue;
} else {
throw new EventBusException("Illegal onEvent method, check for typos: " + method);
}
}
Class> eventType = parameterTypes[0];
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(methodName);
methodKeyBuilder.append('>').append(eventType.getName());
//拼接key,方法名字+">"+参数类名
String methodKey = methodKeyBuilder.toString();
if (eventTypesFound.add(methodKey)) {
// 加入观测者列表
subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));
}
}
} else if (!skipMethodVerificationForClasses.containsKey(clazz)) {
Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "."
+ methodName);
}
}
}
//对比查找类名,相同跳出方法
if (name.equals(stuckClassName)) {
break;
}
//搜索父类的方法
clazz = loadClass(loader, clazz.getSuperclass());
}
if (subscriberMethods.isEmpty()) {
//没有event方法将抛出异常
throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "
+ eventMethodName);
} else {
synchronized (methodCache) {
//key:类名+"."+方法前缀(默认onEvent)
//加入缓存方法
methodCache.put(key, subscriberMethods);
}
return subscriberMethods;
}
}
订阅监听者
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
subscribed = true;
Class> eventType = subscriberMethod.eventType;
// 获取envnt的方法列表,key为方法参数的类全名
CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//检查重复注册
for (Subscription subscription : subscriptions) {
if (subscription.equals(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true);
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
//插入订阅列表,优先级越高,排越签名,加优先执行
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
subscriptions.add(i, newSubscription);
break;
}
}
List> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
//执行粘性事件
if (sticky) {
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
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, Looper.getMainLooper() == Looper.myLooper());
}
}
}
发送事件
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List
发送粘性事件,先缓存event,在上面订阅时将执行方法
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
post(event);
}
取消粘性事件,将事件在缓存中移除
public boolean removeStickyEvent(Object event) {
synchronized (stickyEvents) {
Class extends Object> eventType = event.getClass();
Object existingEvent = stickyEvents.get(eventType);
if (event.equals(existingEvent)) {
stickyEvents.remove(eventType);
return true;
} else {
return false;
}
}
}
反注册方法
public synchronized void unregister(Object subscriber) {
List> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class> eventType : subscribedTypes) {
//移除订阅的方法,通过event类型循环一次
unubscribeByEventType(subscriber, eventType);
}
//移除注册的对象
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
private void unubscribeByEventType(Object subscriber, Class> eventType) {
List 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--;
}
}
}
}