—— 迷茫是什么?迷茫是大事干不了,小事不想干。能力配不上欲望,才华配不上梦想。
前言
时隔多年,那些曾经学过且用过的知识早已记忆模糊。如果不反复研究学习,使用起来也会很生涩,如新知识一样。本编为巩固EventBus所写。一个人为什么要努力,因为喜欢的东西很贵想去的地方都很远,想爱的人很完美。
一、简介
官方文档:https://greenrobot.org/eventbus/documentation/
Github:https://github.com/greenrobot/EventBus
(1)是什么:是一个事件发布/订阅的轻量级框架。基于观察者模式,实现组件间的通讯。代码简洁且解耦。
(2)有什么用:可以替代传统的Intent,Handler,Broadcast或接口函数。
二、基本使用
(1)添加依赖 (不是最新) 基于以前学过的版本
implementation 'org.greenrobot:eventbus:3.0.0'
(2)定义消息事件(可以配置传递参数)
public static class MessageEvent { /* Additional fields if needed */ }
(3)定义接收事件的线程方法(发送的事件,将在该方法中收到)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
(4)EventBus初始化 (与广播相似,需要订阅与取消)
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
(5)发送事件
EventBus.getDefault().post(new MessageEvent());
(6)添加混淆
-keepattributes *Annotation*
-keepclassmembers class * {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
简单的整理了一下 。正确姿势参考官方文档。
三、源码分析
(1)EventBus.getDefault()
* 单例模式 双重效验锁 线程安全 懒加载
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
* 使用构建者配置EventBus 属性
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
this(DEFAULT_BUILDER);
}
* 属性简介
EventBus(EventBusBuilder builder) {
* 保存Event集合
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
* 线程调度
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
* 索引
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
* EventBus订阅方法
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
* EventBus日志
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
* 无消息发送
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
* 异常事件
throwSubscriberException = builder.throwSubscriberException;
* EventBus继承关系
eventInheritance = builder.eventInheritance;
* 线程池
executorService = builder.executorService;
}
(2)EventBus.getDefault().register(this)
* 注册给定的订阅方以接收事件
public void register(Object subscriber) {
* 利用反射获取订阅的类
Class<?> subscriberClass = subscriber.getClass();
* 根据订阅的类找到 该类下的订阅方法 -> 1
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
* 便利所有的订阅方法
for (SubscriberMethod subscriberMethod : subscriberMethods) {
* --> 2
subscribe(subscriber, subscriberMethod);
}
}
}
1.subscriberMethodFinder.findSubscriberMethods(subscriberClass)
* 获取所有的订阅方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
* 判断是否已缓存
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
* ignoreGeneratedIndex 忽略生成的索引 默认为false
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
* 通过反射获取到订阅方法列表 -> 1.1
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;
}
}
1.1.findUsingInfo(Class<?> subscriberClass)
* 通过反射获取到订阅方法列表
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
* 创建FindState 并初始化
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
* 判断findState是否已经有缓存订阅信息
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 {
* 利用反射机制 将订阅方法信息 存储在findState 中
findUsingReflectionInSingleClass(findState);
}
* 移除订阅类
findState.moveToSuperclass();
}
* 回收FindState对象,获取订阅方法列表
return getMethodsAndRelease(findState);
}
2.subscribe(Object subscriber, SubscriberMethod subscriberMethod)
* 判断是否已经注册/订阅过该事件
* 按照优先级缓存订阅事件
* 判断是否已经缓存在typesBySubscriber中
* 判断是否是粘性事件 并分发粘性事件
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);
}
}
* 按照优先级缓存订阅事件 subscriptionsByEventType
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;
}
}
* 判断是否已经缓存在typesBySubscriber中
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
* 判断是否是粘性事件 并分发粘性事件
if (subscriberMethod.sticky) {
if (eventInheritance) {
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);
* 分发事件 -->2.1
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
2.1checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent)
* 判断粘性事件是否为空
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, Looper.getMainLooper() == Looper.myLooper());
}
}
* 根据线程模式进行事件分发
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 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);
}
}
* 将事件添加到 PendingPostQueue 队列中 执行handler 从队列冲取出消息进行处理 并利用反射 执行订阅方法
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");
}
}
}
}
总结:
1.利用反射获取到订阅类的所有订阅方法
2.判断是否已经注册/订阅过该事件
3.按照优先级缓存订阅事件
4.判断是否是粘性事件 并分发粘性事件 (1)同一个线程 利用反射 执行订阅方法 (2)不同线程 将事件添加到 PendingPostQueue 队列中 执行handler 从队列冲取出消息进行处理 并利用反射 执行订阅方法
(3)EventBus.getDefault().post(new MessageEvent());
* 发送事件
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()) {
* 循环分发事件 -->1
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
1.postSingleEvent(eventQueue.remove(0), postingState);
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);
* --> 2
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
* 若没有找到订阅方法 则调用NoSubscriberEvent
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
Log.d(TAG,"No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
2.postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)
* 从subscriptionsByEventType中获取订阅方法
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;
}
总结:
1.获取当前线程的信息,将事件添加到当前线程的队列中
2.判断是否正在分发 不是则执行postSingleEvent 分发事件
3.判断是否有继承关系
是:获取所有类的对象 包含父类与接口 调用postSingleEventForEventType分发事件
否:调用postSingleEventForEventType分发事件
4.若没有找到订阅方法 则分发给NoSubscriberEvent
介绍到这里就结束了 睡觉去了
四、内容推荐
若您发现文章中存在错误或不足的地方,希望您能指出!