源代码
GitHub源代码
本文目标
理解EventBus的核心流程
基本用法
现在有两个页面,MainActivity 和 TestActivity,在MainActivity中注册EventBus事件,然后在TestActivity中发射事件
public class MainActivity extends AppCompatActivity {
private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册
EventBus.getDefault().register(this);
// 进入测试界面
mTv = (TextView) findViewById(R.id.test_tv);
mTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
});
}
/**
* threadMode 执行的线程方式
* priority 执行的优先级
* sticky 粘性事件
*/
@Subscribe(threadMode = ThreadMode.MAIN,priority = 50,sticky = true)
public void test1(String msg){
// 如果有一个地方用 EventBus 发送一个 String 对象,那么这个方法就会被执行
Log.i("TAG","msg1 = "+msg);
mTv.setText(msg);
}
/**
* threadMode 执行的线程方式
* priority 执行的优先级,值越大优先级越高
* sticky 粘性事件
*/
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = true)
public void test2(String msg){
// 如果有一个地方用 EventBus 发送一个 String 对象,那么这个方法就会被执行
Log.i("TAG","msg2 = "+msg);
mTv.setText(msg);
}
@Override
protected void onDestroy() {
// 解绑
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
在TestActivity中去发射事件
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
findViewById(R.id.test_tv).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post("今天天气真晴朗");
finish();
}
});
}
}
ok,基本用法已经展示完毕,有没有发现其实EventBus在MainActivity一共干了3件事
1.注册一个事件
EventBus.getDefault().register(this);
2.然后定义一个方法接受事件
@Subscribe(threadMode = ThreadMode.MAIN,priority = 50,sticky = true)
public void test1(String msg){
}
3.最后在页面销毁的时候解绑事件
EventBus.getDefault().unregister(this);
在TestActivity中就发射了一个事件
EventBus.getDefault().post("今天天气真晴朗");
这以上是EventBus最最基础的用法,我们就从这里开始分析,首先我们从EventBus.getDefault().register(this) 注册事件开始分析
1.EventBus.getDefault().register()
public void register(Object subscriber) {
// 首先获得class对象
Class<?> subscriberClass = subscriber.getClass();
// 通过 subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod
// 里包含了这个方法的 Method 对象,以及将来响应订阅是在哪个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优
// 先级 priority ,以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的所有 Subscriber 注解方法属性。
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 订阅
subscribe(subscriber, subscriberMethod);
}
}
}
上面的方法
- 1.首先获得class对象
- 然后通过 subscriberMethodFinder 来找到订阅者订阅了哪些事件.返回一个 SubscriberMethod 对象的 List, SubscriberMethod里包含了这个方法的 Method 对象,以及将来响应订阅是在哪个线程的 ThreadMode ,以及订阅的事件类型 eventType ,以及订阅的优先级 priority ,以及是否接收粘性 sticky 事件的 boolean 值,其实就是解析这个类上的所有 Subscriber 注解方法属性。
具体的如何获取 List<SubscriberMethod> 集合代码如下
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 先从缓存里面读取,订阅者的 Class
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex。
// ignoreGeneratedIndex的默认值为false,可以通过EventBusBuilder来设置它的值
if (ignoreGeneratedIndex) {
// 利用反射来获取订阅类中所有订阅方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
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) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 寻找某个类中的所有事件响应方法
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass(); //继续寻找当前类父类中注册的事件响应方法
}
return getMethodsAndRelease(findState);
}
// 从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
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 循环所有方法
for (Method method : methods) {
// 获取方法访问修饰符
int modifiers = method.getModifiers();
// 找到所有声明为 public 的方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();// 获取参数的的 Class
if (parameterTypes.length == 1) {// 只允许包含一个参数
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 获取事件的 Class ,也就是方法参数的 Class
Class<?> eventType = parameterTypes[0];
// 检测添加
if (findState.checkAdd(method, eventType)) {
// 获取 ThreadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 往集合里面添加 SubscriberMethod ,解析方法注解所有的属性
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");
}
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
// FindState 涉及到 享元设计模式
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();
}
// 释放 findState 享元模式
return getMethodsAndRelease(findState);
}
第一步:
findSubscriberMethods() ,其实就做了一件事,
去解析注册者对象的所有方法,并且找出带有注解 Subscribe 注解的方法,
然后通过Annotation解析所有细节参数 (threadModel , priority , sticky , EventType , method),
把这些参数封装成一个 SubscriberMethod , 添加到集合返回
就是这个 List<SubscriberMethod> subscriberMethods 集合了,这个SubscriberMethod里面包含
- threadModel 线程方式
- priority 执行的优先级
- sticky 是否黏性事件
- EventType事件类型 ,本例子中就是 String.class
- method 方法对象,本例子中是 test1()和test2()的 Method 对象
说白了就是这个类上的所有 Subscriber 注解方法属性
第二步:
subscribe()
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取方法参数的 class
Class<?> eventType = subscriberMethod.eventType;
// 创建一个 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 获取订阅了此事件类的所有订阅者信息列表
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
// 线程安全的 ArrayList
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<?>>
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 将此事件类加入 订阅者事件类列表中
subscribedEvents.add(eventType);
// 处理粘性事件
if (subscriberMethod.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);
}
}
}
解析所有 SubscriberMethod 的eventType,然后按照要求解析成
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType 的格式
- key : eventType 该例子中就是 String.class
- value : Subscription 的列表,
Subscription 包含两个属性 subscriber 订阅者(反射执行对象即MainActivity) , SubscriberMethod(注解方法的所有属性参数值)
到这里,不知道小伙伴们是否已经能够看明白EventBus的套路了呢?我们可以猜一下,就这一个register方法已经把数据解析成了 key是 String.class,值是List,然后List的元素是Subscription,该元素中又包含 MainActivity.class 和SubscriberMethod(注解方法所有属性封装对象),那接下来肯定是反射啊,直接调用method.invoke()方法就执行了
2.EventBus.getDefault().post()
public void post(Object event) {
// currentPostingThreadState 是一个 ThreadLocal,
// 他的特点是获取当前线程一份独有的变量数据,不受其他线程影响。
// 这个在 Handler 里面有过源码分析
PostingThreadState postingState = currentPostingThreadState.get();
// postingState 就是获取到的线程独有的变量数据
List<Object> eventQueue = postingState.eventQueue;
// 把 post 的事件添加到事件队列
eventQueue.add(event);
// 如果没有处在事件发布状态,那么开始发送事件并一直保持发布状态
if (!postingState.isPosting) {
// 是否是主线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
// isPosting = true
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 获取当前线程状态 postingState 。currentPostingThreadState 其实就是一个 ThreadLocal 类的对象,不同的线程根据自己独有的索引值可以得到相应属于自己的 postingState 数据。
- 然后把事件 event 加入到 eventQueue 队列中排队。
- 循环遍历 eventQueue ,取出事件发送事件。发送单个事件是调用 postSingleEvent(Object event, PostingThreadState postingState) 方法。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
// 得到事件的Class
Class<?> eventClass = event.getClass();
// 是否找到订阅者
boolean subscriptionFound = false;
// 如果支持事件继承,默认为支持
if (eventInheritance) {
// 查找 eventClass 的所有父类和接口
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
// 依次向 eventClass 的父类或接口的订阅方法发送事件
// 只要有一个事件发送成功,返回 true ,那么 subscriptionFound 就为 true
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
// 发送事件
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
// 如果没有订阅者
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));
}
}
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 得到Subscription 列表
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍历 subscriptions
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 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);
}
}
遍历 Subscription ,找到符合的方法调用方法的 method.invoke()执行
3.EventBus.getDefault().unregister()
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 {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 获取事件类的所有订阅信息列表,将订阅信息从订阅信息集合中移除,同时将订阅信息中的active属性置为FALSE
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) {
// 将订阅信息激活状态置为FALSE
subscription.active = false;
// 将订阅信息从集合中移除
subscriptions.remove(i);
i--;
size--;
}
}
}
}
至此全部分析完毕
网友评论