俗话说,好记性不如烂笔头。特别是程序这一块,你自己不动手敲敲永远感觉迷迷糊糊的,所以,我们在学习一个新知识点的时候,首先要知道它怎么用,然后还要去研究它为什么这么用,即它里面的原理到底是什么样子的。关于EventBus,我想就不用去说怎么用了,因为它用起来确实很方便。但是,如果我问你,你真的懂EventBus吗?你知道里面用到了哪些设计模式吗?可能很多人会一脸懵逼状态,不要怕,下面我们就一起来看看吧!
- 什么是EventBus
EventBus是由greenrobot组织贡献(该组织还贡献了greenDAO),一个Android事件发布/订阅轻量级框架;
通过解耦发布者和订阅者简化Android事件传递
EventBus可以代替Android传统的Intent,Handler,Broadcast或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法。代码简洁,是一种发布订阅设计模式(
观察者设计模式)
- EventBus三要素
既然EventBus用的是设计者观察者模式,那么肯定具备观察者设计模式的三要素(观察者,被观察者,事件),那么在EventBus中对应的就是Event事件(可以是任意对象),Subscriber 事件订阅者,Publisher 事件的发布者
1.Event:
可以是任何事件
2.Subscriber :
在EventBus3.0之前我们必须定义以onEvent开头的那几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe(),并且指定线程模型,默认是POSTING
3.Publisher :
我们可以在任意线程里发布事件,一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。
3. EventBus线程模型
既然EventBus可以在任意地方发布事件,那么也就意味着EventBus内部对线程进行了处理。EventBus线程模型共有四种:
1.POSTING:
事件的处理和事件的发送在相同的进程,所以事件处理时间不应太长,不然影响事件的发送线程,而这个线程可能是UI线程
2.MAIN
事件的处理会在UI线程中执行,事件处理不应太长时间
3.MAIN_ORDERED
事件的处理会在UI线程中执行,不过需要排队,如果前一个也是main_ordered 需要等前一个执行完成后才执行,在主线程中执行,可以处理更新ui的操作。不过需要排队,如果前一个也是main_ordered 需要等前一个执行完成后才执行,在主线程中执行,可以处理更新ui的操作。
4.BACKGROUND
事件的处理会在一个后台线程中执行,尽管是在后台线程中运行,事件处理时间不应太长。如果事件分发在主线程,事件会被加到一个队列中,由一个线程依次处理这些事件,如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。如果事件分发在后台线程,事件会立即执行处理。
5.ASYNC
事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,每个事件会开启一个线程(有线程池)
前面的这些都是铺垫,现在才开始进入主菜,Are you ready?
先贴出一个简单的使用的例子
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 1class GuideActivity : BaseActivity() {
2
3 private lateinit var mProgress: MyProgressBar
4
5 override fun onCreate(savedInstanceState: Bundle?) {
6 super.onCreate(savedInstanceState)
7 setContentView(R.layout.activity_guide)
8 EventBus.getDefault().register(this)
9 initView()
10 initData()
11 }
12
13 private fun initView() {
14 mProgress = findViewById(R.id.progress)
15 }
16
17 private fun initData() {
18 mProgress.start(3000)
19 }
20
21 @Subscribe(threadMode = ThreadMode.MAIN)
22 public fun messageEventBus(messageEvent: MessageEvent){
23 startActivity(Intent(this, SplashActivity::class.java))
24 }
25
26 override fun onStop() {
27 super.onStop()
28 EventBus.getDefault().unregister(this)
29 }
30}
31
我们第一个要研究的方法就是EventBus.getDefault.register(this);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 1 // 在这里我们以GuideActivity来进行分析
2 public void register(Object subscriber) {
3 // 在我们注册的时候subscriber就是我们传递进来的GuideActivity,即:subscriber = GuideActivity
4 // 获取传递进来的事件订阅者的类名 subscriberClass = GuideActivity.class
5 Class<?> subscriberClass = subscriber.getClass();
6 // SubscriberMethod:用来存放事件订阅者的一些基本信息(包括Method,ThreadMode,EventType,Priority,sticky)
7 // 通过事件订阅者的类名来找到该类中标记为Subscribe的方法,并把该方法的所有信息封装成SubscriberMethod对象
8 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
9 synchronized (this) {
10 for (SubscriberMethod subscriberMethod : subscriberMethods) {
11 // 遍历循环每一个SubscriberMethod
12 subscribe(subscriber, subscriberMethod);
13 }
14 }
15 }
16
接下来我们看看findSubscriberMethods()里面到底是做了一些什么操作
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69 1########################################### SubscriberMethodFinder ################################
2 private final boolean ignoreGeneratedIndex;
3
4 private static final int POOL_SIZE = 4;
5 private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
6
7 SubscriberMethodFinder(List<SubscriberInfoIndex> subscriberInfoIndexes, boolean strictMethodVerification,
8 boolean ignoreGeneratedIndex) {
9 this.subscriberInfoIndexes = subscriberInfoIndexes;
10 this.strictMethodVerification = strictMethodVerification;
11 this.ignoreGeneratedIndex = ignoreGeneratedIndex;
12 }
13
14
15 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
16 // METHOD_CACHE是啥?在上面找到这个
17 // private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
18 // 看到这里我们就懂了,原来METHOD_CACHE是一个集合,一个以Class<?>为key,一个List<SubscriberMethod>为value的值的map集合
19 // 第一次的时候肯定是空的,所以我们走下面的,第二次的话直接从缓存里面读取,然后直接返回,从而避免了通过反射再次去拿取
20 List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
21 if (subscriberMethods != null) {
22 return subscriberMethods;
23 }
24 // ignoreGeneratedIndex是啥?从上面可知是在构造函数里面赋值的,那么SubscriberMethodFinder是在哪里被实例化的呢?
25 // 原来是在EventBus的构造函数里面被实例化的,为了方便,我在下面直接贴出来了
26 // 而最终的赋值是在EventBusBuilder里面,而默认是false,所以走下面的findUsingInfo
27 if (ignoreGeneratedIndex) {
28 subscriberMethods = findUsingReflection(subscriberClass);
29 } else {
30 subscriberMethods = findUsingInfo(subscriberClass);
31 }
32 // 当subscriberMethods为空的时候,会抛出一个异常,其实到这里我们就明白了,
33 // 凡是被register()的类必须要有事件订阅者,即有被@Subscribe标注的方法
34 if (subscriberMethods.isEmpty()) {
35 throw new EventBusException("Subscriber " + subscriberClass
36 + " and its super classes have no public methods with the @Subscribe annotation");
37 } else {
38 // 当subscriberMethods不为空的时候,直接添加到集合里面,然后返回
39 METHOD_CACHE.put(subscriberClass, subscriberMethods);
40 return subscriberMethods;
41 }
42
43 // 那么在findUsingInfo里面又做了哪些事情呢?
44 }
45
46 ########################################### EventBus ################################
47 EventBus(EventBusBuilder builder) {
48 logger = builder.getLogger();
49 subscriptionsByEventType = new HashMap<>();
50 typesBySubscriber = new HashMap<>();
51 stickyEvents = new ConcurrentHashMap<>();
52 mainThreadSupport = builder.getMainThreadSupport();
53 mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
54 backgroundPoster = new BackgroundPoster(this);
55 asyncPoster = new AsyncPoster(this);
56 indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
57 subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
58 builder.strictMethodVerification, builder.ignoreGeneratedIndex);
59 logSubscriberExceptions = builder.logSubscriberExceptions;
60 logNoSubscriberMessages = builder.logNoSubscriberMessages;
61 sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
62 sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
63 throwSubscriberException = builder.throwSubscriberException;
64 eventInheritance = builder.eventInheritance;
65 executorService = builder.executorService;
66 }
67
68
69
那么在findUsingInfo里面又做了哪些事情呢?
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 1private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
2 // FindState又是啥?不要急,我们慢慢来看
3 // 我们看单词意思来猜一下,这个应该是保存传递过来的GuideActivity.class类里面被标注为@Subscribe方法的信息的实体类
4 // 点进去看一下,哈哈哈,看了下面的代码是不是恍然大悟,原来真的是这样
5 FindState findState = prepareFindState();
6 findState.initForSubscriber(subscriberClass);
7 while (findState.clazz != null) {
8 // 当Guide.class不为空的时候,拿取对应的信息并返回
9 findState.subscriberInfo = getSubscriberInfo(findState);
10 if (findState.subscriberInfo != null) {
11 SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
12 for (SubscriberMethod subscriberMethod : array) {
13 if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
14 findState.subscriberMethods.add(subscriberMethod);
15 }
16 }
17 } else {
18 // 当Guide.class为空的时候,拿取对应的信息并返回
19 findUsingReflectionInSingleClass(findState);
20 }
21 findState.moveToSuperclass();
22 }
23 // 返回List<SubscriberMethod>集合
24 return getMethodsAndRelease(findState);
25 }
26
27 ########################################## FindState ##############################
28 static class FindState {
29 final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
30 final Map<Class, Object> anyMethodByEventType = new HashMap<>();
31 final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
32 final StringBuilder methodKeyBuilder = new StringBuilder(128);
33
34 Class<?> subscriberClass;
35 Class<?> clazz;
36 boolean skipSuperClasses;
37 SubscriberInfo subscriberInfo;
38
39 void initForSubscriber(Class<?> subscriberClass) {
40 this.subscriberClass = clazz = subscriberClass;
41 skipSuperClasses = false;
42 subscriberInfo = null;
43 }
44
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 1// 关键代码来了
2private void findUsingReflectionInSingleClass(FindState findState) {
3 Method[] methods;
4 try {
5 // This is faster than getMethods, especially when subscribers are fat classes like Activities
6 // 找到GuideActivity.class的所有方法
7 methods = findState.clazz.getDeclaredMethods();
8 } catch (Throwable th) {
9 // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
10 methods = findState.clazz.getMethods();
11 findState.skipSuperClasses = true;
12 }
13 // 遍历所有方法
14 for (Method method : methods) {
15 // 获取方法上面的修饰符
16 int modifiers = method.getModifiers();
17 // 修饰符必须为public
18 if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
19 // 拿到方法参数,即如果你是写的String message,那么拿到的值就是String.class
20 Class<?>[] parameterTypes = method.getParameterTypes();
21 // 只允许带一个参数
22 if (parameterTypes.length == 1) {
23 // 拿到注解为Subscribe
24 Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
25 if (subscribeAnnotation != null) {
26 // 拿到注解为Subscribe里面的参数信息
27 Class<?> eventType = parameterTypes[0];
28 if (findState.checkAdd(method, eventType)) {
29 ThreadMode threadMode = subscribeAnnotation.threadMode();
30 // 将所有的参数信息封装成SubscriberMethod并添加到集合中
31 findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
32 subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
33 }
34 }
35 } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
36 String methodName = method.getDeclaringClass().getName() + "." + method.getName();
37 throw new EventBusException("@Subscribe method " + methodName +
38 "must have exactly 1 parameter but has " + parameterTypes.length);
39 }
40 } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
41 String methodName = method.getDeclaringClass().getName() + "." + method.getName();
42 throw new EventBusException(methodName +
43 " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
44 }
45 }
46}
47
48
别急哈,上面的分析才只是分析了这行代码
1
2 1List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
2
接下来我们继续向下走,分析这行代码
1
2 1subscribe(subscriber, subscriberMethod);
2
注意这里面带了两个参数:subscriber其实是GuideActivity.class,subscriberMethod就是被标记为@Subscribe方法的所有信息组合起来的实例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
56
57
58
59
60
61
62
63
64
65
66 1private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
2 // 拿到对应的类型,注意这里的eventType应该是String.class,而不是GuideActivity.class,千万别搞混了
3 Class<?> eventType = subscriberMethod.eventType;
4 // 这里的Subscription又是啥呢?点进去看看
5 Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
6 // subscriptionsByEventType是一个集合,用来保存以Class为key,以CopyOnWriteArrayList<Subscription>为value的集合
7 // 注意这里的key是方法里面的参数类型,即String
8 // 所以这里的key是String.class等等
9 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
10 // 第一次为空
11 if (subscriptions == null) {
12 // 实例化集合
13 subscriptions = new CopyOnWriteArrayList<>();
14 // 将数据添加到Map集合中
15 subscriptionsByEventType.put(eventType, subscriptions);
16 } else {
17 // 当不为空的时候且集合里面有这个值,就抛出异常
18 // 不信的同学可以在同一个类里面注册两次试试哦,看会不会抛出这个异常
19 if (subscriptions.contains(newSubscription)) {
20 throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
21 + eventType);
22 }
23 }
24
25 // 根据优先级进行排序
26 int size = subscriptions.size();
27 for (int i = 0; i <= size; i++) {
28 if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
29 subscriptions.add(i, newSubscription);
30 break;
31 }
32 }
33
34 // 这里又来一个集合,这个集合是干吗的呢?
35 // 从上面可以推导出subscriber==GuideActivity.class
36 // 所以我们可以知道,typesBySubscriber保存的是以GuideActivity.class为key,以List为value
37 // 而subscribedEvents里面保存的又是eventType,即String.class
38 // 最终的结论是:typesBySubscriber保存的是以对象为key,以被标记为@Subscribe方法里面带参的参数类型为值的集合为value
39 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
40 if (subscribedEvents == null) {
41 subscribedEvents = new ArrayList<>();
42 typesBySubscriber.put(subscriber, subscribedEvents);
43 }
44 subscribedEvents.add(eventType);
45
46 if (subscriberMethod.sticky) {
47 if (eventInheritance) {
48 // Existing sticky events of all subclasses of eventType have to be considered.
49 // Note: Iterating over all events may be inefficient with lots of sticky events,
50 // thus data structure should be changed to allow a more efficient lookup
51 // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
52 Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
53 for (Map.Entry<Class<?>, Object> entry : entries) {
54 Class<?> candidateEventType = entry.getKey();
55 if (eventType.isAssignableFrom(candidateEventType)) {
56 Object stickyEvent = entry.getValue();
57 checkPostStickyEventToSubscription(newSubscription, stickyEvent);
58 }
59 }
60 } else {
61 Object stickyEvent = stickyEvents.get(eventType);
62 checkPostStickyEventToSubscription(newSubscription, stickyEvent);
63 }
64 }
65 }
66
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 1// 保存对象以及SubscriberMethod
2// 形象一点就是保存GuideActivity.class和GuideActivity类里面标记为@Subscriber方法的SubscriberMethod对象
3final class Subscription {
4 final Object subscriber;
5 final SubscriberMethod subscriberMethod;
6 /**
7 * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
8 * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
9 */
10 volatile boolean active;
11
12 Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
13 this.subscriber = subscriber;
14 this.subscriberMethod = subscriberMethod;
15 active = true;
16 }
17
18 @Override
19 public boolean equals(Object other) {
20 if (other instanceof Subscription) {
21 Subscription otherSubscription = (Subscription) other;
22 return subscriber == otherSubscription.subscriber
23 && subscriberMethod.equals(otherSubscription.subscriberMethod);
24 } else {
25 return false;
26 }
27 }
28
29 @Override
30 public int hashCode() {
31 return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
32 }
33}
34
到这里我们的register()方法就结束了。
接下来进入到EventBus.getDefault.post();
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 1// 有木有很熟悉的感觉,看过Handler源码的同学应该对这个很熟悉了吧
2// ThreadLocal是为了保证线程安全的,在这里我就不做过多的说明了,不懂的同学可以自己去网上查查
3private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
4 @Override
5 protected PostingThreadState initialValue() {
6 return new PostingThreadState();
7 }
8};
9
10/** Posts the given event to the event bus. */
11public void post(Object event) {
12 // PostingThreadState这个类是干嘛用的呢?不要慌,点击进去看看
13 PostingThreadState postingState = currentPostingThreadState.get();
14 List<Object> eventQueue = postingState.eventQueue;
15 // 将事件加入到队列当中
16 eventQueue.add(event);
17 // 第一次进来肯定是false
18 if (!postingState.isPosting) {
19 // 判断事件发布是不是在主线程
20 postingState.isMainThread = isMainThread();
21 // 改变事件的状态,表示该事件已经被发布了
22 postingState.isPosting = true;
23 if (postingState.canceled) {
24 throw new EventBusException("Internal error. Abort state was not reset");
25 }
26 try {
27 // 哈哈哈哈,有木有很熟悉的感觉,在Handler源码里面MessageQueue也是通过一个while循环不断的去发布Message
28 while (!eventQueue.isEmpty()) {
29 postSingleEvent(eventQueue.remove(0), postingState);
30 }
31 } finally {
32 postingState.isPosting = false;
33 postingState.isMainThread = false;
34 }
35 }
36}
37
38// 我们可以把这个类理解为辅助类,主要是用来记录发布者线程状态
39final static class PostingThreadState {
40 final List<Object> eventQueue = new ArrayList<>();
41 boolean isPosting;
42 boolean isMainThread;
43 Subscription subscription;
44 Object event;
45 boolean canceled;
46}
47
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 1private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
2 // 注意,这里的event是你传递的值,比如像1,2,"12"等等
3 // 拿到当前发布事件的类型(比如String.class)
4 Class<?> eventClass = event.getClass();
5 boolean subscriptionFound = false;
6 // eventInheritance这个字段是干什么用的呢?
7 // 比如 A extends B implements C 发布者post(A),那么找订阅者的时候不仅要找订阅了事件A的订阅者
8 // 还要找订阅了B和C的订阅者
9 if (eventInheritance) {
10 // 找到事件的所有父类和所有实现的接口,以Class形式返回
11 // 可能最终返回的结果是String.class,Message.class
12 List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
13 int countTypes = eventTypes.size();
14 // 遍历循环
15 for (int h = 0; h < countTypes; h++) {
16 Class<?> clazz = eventTypes.get(h);
17 // 注意这3个参数的意义
18 // event:你传递的实际值,比如像1,2,"12"等等
19 // postingState:记录发布者线程状态的实体类
20 // clazz:拿到当前发布事件的实例,比如String.class,Message.class
21 subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
22 }
23 } else {
24 // 这行就比较好理解了吧,当没有父类也没有接口的时候,直接使用实例
25 subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
26 }
27 if (!subscriptionFound) {
28 if (logNoSubscriberMessages) {
29 logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
30 }
31 if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
32 eventClass != SubscriberExceptionEvent.class) {
33 post(new NoSubscriberEvent(this, event));
34 }
35 }
36}
37
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 1// 关键代理来了,好好看哟
2private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
3 // 还记得Subscription这个里面存了什么东西吗?
4 // 实际上Subscription存储了两样东西,一个是Object subscriber(即GuideActivity.class),还有一个是标记为@Subscribe的方法封装的SubscriberMethod
5 CopyOnWriteArrayList<Subscription> subscriptions;
6 synchronized (this) {
7 // 在这里我以String.class为例
8 // 拿出所有的以String.class为key的CopyOnWriteArrayList<Subscription>
9 subscriptions = subscriptionsByEventType.get(eventClass);
10 }
11 // 当CopyOnWriteArrayList<Subscription>不为空的时候遍历集合
12 if (subscriptions != null && !subscriptions.isEmpty()) {
13 // 拿到集合里面的每一个Subscription
14 for (Subscription subscription : subscriptions) {
15 // 拿到Subscription里面的具体信息并赋值给PostingThreadState
16 postingState.event = event;
17 postingState.subscription = subscription;
18 boolean aborted = false;
19 try {
20 // 根据线程模型选择最后的事件处理方式
21 postToSubscription(subscription, event, postingState.isMainThread);
22 aborted = postingState.canceled;
23 } finally {
24 postingState.event = null;
25 postingState.subscription = null;
26 postingState.canceled = false;
27 }
28 if (aborted) {
29 break;
30 }
31 }
32 return true;
33 }
34 return false;
35}
36
37private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
38 switch (subscription.subscriberMethod.threadMode) {
39 case POSTING:// 默认线程(在哪个线程订阅就在哪个线程执行)
40 invokeSubscriber(subscription, event);
41 break;
42 case MAIN: // 主线程
43 if (isMainThread) { // 如果是在主线程,直接执行
44 invokeSubscriber(subscription, event);
45 } else { // 否则加入到事件队列中进行处理
46 mainThreadPoster.enqueue(subscription, event);
47 }
48 break;
49 case MAIN_ORDERED:// 在主线程,但是和MAIN的区别就是事件总是入队后交付给用户,所以调用后会立即返回
50 if (mainThreadPoster != null) {
51 mainThreadPoster.enqueue(subscription, event);
52 } else {
53 // temporary: technically not correct as poster not decoupled from subscriber
54 invokeSubscriber(subscription, event);
55 }
56 break;
57 case BACKGROUND: // 订阅者将在后台线程中被调用
58 if (isMainThread) {
59 backgroundPoster.enqueue(subscription, event);
60 } else {
61 invokeSubscriber(subscription, event);
62 }
63 break;
64 case ASYNC: // 事件处理程序方法在单独的线程中调用。这始终与发布线程和主线程无关
65 asyncPoster.enqueue(subscription, event);
66 break;
67 default:
68 throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
69 }
70}
71
这里我们稍微总结一下:在post()方法里面到底干了什么事情?其实就是一句话:
typesBySubscriber 找出满足需求的然后反射执行对应的方法
看到这里大家心里有没有点疑问呢?反正我是有的,具体是什么呢?大家可以好好揣摩一下我上面的那句话。
假设现在有这么一种情况:Activity1里面发布了一个test(String text)方法,Activity2里面也发布了一个test(String text)方法,然后我从Activity1跳转到Activity2,回退的时候执行post()方法,理论上Activity1和Activity2里面的test(String text)都应该被触发,但是这个时候Activity2已经被销毁了,那岂不是应用程序要闪退了?这个时候我们的unregister就闪亮登场了
接下来进入到EventBus.getDefault.unregister();
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 1 /** Unregisters the given subscriber from all event classes. */
2 // unregister代码很简单
3public synchronized void unregister(Object subscriber) {
4 // 判断当前类是否在Map<Object, List<Class<?>>> typesBySubscriber;
5 List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
6 // 如果存在的话,首先从Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;移除该实例注册的所有订阅事件
7 // 然后在Map<Object, List<Class<?>>> typesBySubscriber;中移除
8 if (subscribedTypes != null) {
9 for (Class<?> eventType : subscribedTypes) {
10 unsubscribeByEventType(subscriber, eventType);
11 }
12 typesBySubscriber.remove(subscriber);
13 } else {
14 logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
15 }
16}
17
18 /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
19private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
20 List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
21 if (subscriptions != null) {
22 int size = subscriptions.size();
23 for (int i = 0; i < size; i++) {
24 Subscription subscription = subscriptions.get(i);
25 if (subscription.subscriber == subscriber) {
26 subscription.active = false;
27 subscriptions.remove(i);
28 i--;
29 size--;
30 }
31 }
32 }
33}
34
35
ungister()方法相对于其他方法来说还是比较简单的,我在这里给大家举一个例子大家就更明白了
首先我们要弄懂这两个Map里面到底是存放了些啥?不会总会感觉云里雾里的
1
2
3
4 1
2private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
3private final Map<Object, List<Class<?>>> typesBySubscriber;
4
首先贴两张图
这里我再用文字描述一下:
- Map<Class<?>, CopyOnWriteArrayList<Subscription>>
1》存放的是以String.class,Message.class为key的(String.class,Message.class对应的是被@Subscribe标注的方法里面的参数类型)
2》以CopyOnWriteArrayList<Subscription>为value的集合
2.CopyOnWriteArrayList<Subscription>里面的Subscription是一个实体类,里面包含了
1
2
3
4 1
2final Object subscriber;
3final SubscriberMethod subscriberMethod;
4
1》subscriber代表的是register所在的那个类(比如:GuideActivity.class)
2》subscriberMethod保存的是被@Subscribe标注的方法组合的实体类
- Map<Object, List<Class<?>>> typesBySubscriber
1》 key是
register所在的那个类(比如:GuideActivity.class)
2》 value是 List<Class<?>>集合,而Class<?> 对应的是被@Subscribe标注的方法里面的参数类型
看到这里你再回头看看unregister()方法,是不是so easy了
好了,到这里,EventBus的所有的源码就分析完了,其实回过头来看感觉也没有那么难,最重要的是静下心来好好看,边看边琢磨,多花点时间总可以搞懂的。最后以一句话结尾吧:天道酬勤,努力才会有收获!!!