Eventbus源码浅析

参考:
Android每周一轮子:EventBus
Android开源框架源码鉴赏:EventBus
EventBus 3.0.0高效使用及源码解析
Android 框架学习2:源码分析 EventBus 3.0 如何实现事件总线
老司机教你 “飙” EventBus 3

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
String message = event.message;
Toast.makeText(this, "收到了消息: " + message, Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}

public void go2secondActivity(View view) {
startActivity(new Intent(this, SecondActivity.class));
}
}

在接受消息的这个Activity中, 我们注册了当前activity, 在activity destroy的时候取消注册, 然后新建一个方法, 添加@Subscribe的注解, 注意只能是public的, 方法名可以随便取, 在这个方法里接收发出的事件.

然后我们在另一个Activity里发出事件

1
2
3
4
5
6
7
8
9
10
11
12
public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}

public void sendMessage(View view) {
EventBus.getDefault().post(new MessageEvent("这是SecondActivity发送的消息"));
}
}

这样在MainActivity里就能接收到发出的消息了

EventBus.getDefault()

首先看EventBus.getDefault()

1
2
3
4
5
6
7
8
9
10
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

这是一个典型的DCL的单例

register(Object subscriber)

我们看一下register()方法

1
2
3
4
5
6
7
8
9
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}

首先获取订阅实例的类, 然后寻找该类中的所有订阅方法, 然后对这些方法调用订阅方法.
看一下这个findSubscriberMethods(Class<?> subscriberClass)方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}
}

首先从缓存中寻找方法, 如果没有, 那就使用反射或者usinginfo来寻找方法, 如果还没有那就要报错了, 说明这个订阅者对象的类以及它的父类中没有public的带有@Subscribe注解的方法.如果找到了, 那就放入缓存.

在这里我打断点发现会使用后面那一种findUsingInfo的方法, 我们看一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
}

再次打了一下断点, 发现还是会走反射的方法(代码中注释的地方), 看一下吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
// 这个比getMethods快多了, 尤其对于像Activity那样庞大的类
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()));
}
}
} 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");
}
}
}

在这里首先获取了订阅者类中的public方法, getDeclaredMethods()getMethods()方法的区别在于: getDeclaredMethods()获取包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法, getMethods()获取所有公用(public)方法包括其继承类的公用方法.
然后遍历这些方法.只有符合这些条件的方法才是符合要求的:

  1. 权限修饰符是public或者procected的(可能还有别的, 但是private是不行的), 非static
  2. 只有一个参数
  3. 含有Subscribe注解
    如果有这样的方法, 那就根据这个方法, 消息类, threadMode, priority, sticky生成一个SubscriberMethod()对象, 然后添加到findState的subscriberMethods集合中去

现在我们回到findUsingInfo(Class<?> subscriberClass)方法, 这里这个findState现在已经保存了那些订阅方法了, 然后把这些方法(包括其中的参数)放在一个集合中然后return出去

现在我回到register(Object subscriber)方法, 在获取了订阅者的所有订阅方法之后, 我们遍历这些方法, 对每一个方法调用subscribe(Object subscriber, SubscriberMethod subscriberMethod)方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// subscriptionsByEventType是一个map, key是消息的class, value是一个list
// list中包含了所有订阅了这个消息的订阅者
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);
}
}

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) {
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);
}
}
}

在这个方法中, 主要做了这些事:

  1. 传入订阅者和事件类型生成一个新的订阅对象
  2. 根据事件类型从map中获取了一个订阅对象的集合, 如果这个集合还不存在, 就new一个, 然后以事件类型为key, 这个集合为value添加到一个map里
  3. 如果这个集合存在, 对这个订阅对象进行检查, 如果订阅对象的集合中已经包含有重复的订阅对象, 就报错, 可以看注释中写的.所以说EventBus.getDefault().register(this)这个方法在同一个类里面是不可以被调用两次的
  4. 遍历这个集合, 按照事件的优先级将新的订阅对象添加到集合中去
  5. 根据订阅者从map中获取了一个消息类型的集合, 如果这个集合还不存在, 就new一个, 将事件类型添加到这个集合中
  6. 黏性事件的处理, 暂时不研究

post(Object event)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public void post(Object event) {
// 获取当前线程的状态
PostingThreadState postingState = currentPostingThreadState.get();
// 获取事件的队列
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;
}
}
}

currentPostingThreadState是一个ThreadLocal, 初始值是new了一个PostingThreadState

看一下postSingleEvent(eventQueue.remove(0), postingState);这句代码吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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));
}
}
}

看一下postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 这个subscriptionsByEventType我们在register的时候见过
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;
}

subscriptionsByEventType是一个map, 我们register的时候也用到过.它的key是事件的class, value是一个Subscription的list. 在这里会根据事件的class, 将所有订阅了这个消息类型的订阅对象(注意不是订阅者而是用订阅者和订阅方法生成的订阅对象)的列表取出来.

我们再看一下postToSubscription(Subscription subscription, Object event, boolean isMainThread)这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case POSTING:
// 默认是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);
}
}

因为subscriberMethod的线程模式默认是POSTING, 所以我们看一下POSTING

1
2
3
4
5
6
7
8
9
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);
}
}

可以看着这里使用了反射, 传入了方法的调用对象订阅者, 和方法参数事件对象, 然后Method.invoke(Object obj, Object... args)

todo(以后有时间了再补充)

黏性事件

所谓的黏性事件大意就是先发出事件, 然后等有对象注册了再立刻调用.大胆猜想就是在注册的时候检查这个订阅方法事件是否是黏性的, 如果是就找到对应这个事件类型的事件, 然后调用.
待续…

四种不同的线程模型

待续…

取消注册

待续…

编译时注解eventBusIndex

待续…

简单总结

简单总结一下Eventbus的原理

  1. EventBus.getDefault().register(this);这一句会扫描这个订阅者中的订阅方法, 将每个方法和订阅者包装成Subscription, 添加到list中, 然后又把list放到以事件类型class对象的map中, 方便以后查找
  2. EventBus.post(Object object)这句会在上面的map中查找所对应的订阅者和订阅方法, 然后使用反射, 让订阅者调用订阅方法, 传入的参数就是这个发送的消息事件

用两张图说明下

  • register

  • post

0%