EventBus相关文章虽然对,作为学习笔记使用,有问题希望能够尽情提出,共同交流
蒋八九
implementation 'org.greenrobot:eventbus:3.1.1'
EventBus.getDefault().register(this);
普通事件的发送:
EventBus.getDefault().post(new MessageEvent("第二页点击后关闭"));
粘性事件的发送:
EventBus.getDefault().postSticky(new MessageEvent("发送Sticky事件"));
普通事件的接收
@Subscribe(threadMode = ThreadMode.MAIN) 主线程接受:
@Subscribe(threadMode = ThreadMode.BACKGROUND) 子线程接受:
@Subscribe(threadMode = ThreadMode.POSTING) 不切换线程接受:
@Subscribe(threadMode = ThreadMode.ASYNC) 异步线程接受:
public void EventMAIN(MessageEvent messageEvent) {
Log.e(TAG, "EventBus:EventMAIN:" + Thread.currentThread());
}
粘性事件的接收:
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void XXX(MessageEvent messageEvent) {
Log.e(TAG, "EventBus:sticky:接受Sticky事件" + messageEvent.getMessage());
}
设计模式:单例,订阅者模式
首先getDefault(),然后register()注册
EventBus.getDefault().register(this);
//这里getDefault主要为了获取构造,初始化三个hashmap,和三个poster
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
//存储被订阅类型(如EventMessage)和订阅者集合(如Subscription对象是个CopyOnWriteArrayList,其中封装了MainActivity和订阅方法subscriberMethod)
subscriptionsByEventType = new HashMap<>();
//存储订阅者(如MainActivity)和被订阅者类型集合(如EventMessage,是个ArrayList)
typesBySubscriber = new HashMap<>();
//粘性事件的集合
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
//主线程poster,继承handler,用来切换到主线程
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
//子线程poster,生成的runnable任务最终通过excecute提交给cacheThreadpool线程池来执行任务
backgroundPoster = new BackgroundPoster(this);
//异步poster,生成的runnable任务最终通过excecute提交给cacheThreadpool线程池来执行任务
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
//这个类用来查找所有被@Subscribe注释的方法的信息
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;
//jdk1.5中的cacheThreadPool线程池
executorService = builder.executorService;
}
register过程:
1、methodfinder对象,使用反射从class中找出所有的方法
2、遍历所有方法,找出满足(被public修饰&&且只有一个入参&&且被@Subscribe注释)的方法集合
3、遍历集合,并添加到三个容器中,即完成注册。
public void register(Object subscriber) {
Class subscriberClass = subscriber.getClass();
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List findSubscriberMethods(Class subscriberClass) {
先从方法换从中查找,有就直接返回了
List subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
这里通过反射查找当前类中的注释方法集合
subscriberMethods = findUsingReflection(subscriberClass);
} else {
先尝试从索引中查找,没有再通过反射方法查找。
subscriberMethods = findUsingInfo(subscriberClass);
}
这里当一个类添加了regist方法,但是找不到满足条件的方法,那么就抛出异常。
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 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);
}
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
首先获取所有的方法。
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
条件一、方法Modifiers修饰语必须是public
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class[] parameterTypes = method.getParameterTypes();
条件二、方法入参个数必须只有一个,否则抛异常提示
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");
}
}
}
当前类找完去父类再继续找一遍,直到找完为止,这里应该把AndroidX也适配上了
void moveToSuperclass() {
if (skipSuperClasses) {
clazz = null;
} else {
clazz = clazz.getSuperclass();
String clazzName = clazz.getName();
if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
clazz = null;
}
}
}
得到所有的subcribeMethods之后,遍历并对subscriptionByEventType、typesBySubscriber进行装箱。
subscriptionByEventType:订阅类型为key,Subscription(class,subscriberMethod)为value;value按优先级大小添加
typesBySubscriber:class为key,subcribeMethods集合为value;
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList 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> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(
if (subscriberMethod.sticky) {
if (eventInheritance) {
Set, Object>> entries = stickyEvents.entrySet();
for (Map.Entry, 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);
}
}
}
1、将消息添加到数组中,就是个arraylist数组。
2、如果支持继承,则将消息事件的父类和接口类都找出来
EventBus.getDefault().post("haha");
public void post(Object event) {
首先拿到postingState对象,然后将event事件添加到ArrayList中去,然后遍历数组进行发送。
PostingThreadState postingState = currentPostingThreadState.get();
List
1、先将事件存放到stickyEvents的map集合中去
2、然后将他当做普通事件发送给当前Activity中的同名事件,当前事件不需要sticky==true。
EventBus.getDefault().postSticky("haha");
首先将事件存放到stickyEvents的map集合中去
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
post(event);
}
当打开另一个类走到subscribe的时候,遍历方法是否是sticky事件,如果是的话,从stickyEvents中获取缓存的粘性事件,调用postSubscribe——>invokeSubscribe将时间发送出去。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
。。。。。。。
if (subscriberMethod.sticky) {
if (eventInheritance) {
Set, Object>> entries = stickyEvents.entrySet();
for (Map.Entry, 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);
}
}
}
优点:3.0使用的编译的时注解,这个类似与ARouter,2.0使用的运行时注解,这个依赖与java的反射规则。