EventBus源码分析

我就是我 2023-07-17 04:57 83阅读 0赞

前言

EventBus是一种用于Android的发布/订阅事件总线。它有很多优点:简化应用组件间的通信;解耦事件的发送者和接收者;避免复杂和容易出错的依赖和生命周期的问题;很快,专门为高性能优化过等等。

源码分析

EventBus源码分析主要分为两个过程:

  1. 订阅事件
  2. 发布事件

在分析订阅事件之前,我们先来分析一下与订阅事件相关的订阅者索引。

订阅者索引

默认情况下,EventBus使用Java反射来查找订阅者信息。订阅者索引是EventBus 3的一个新特性。它可以加速查找订阅者信息的过程,是一个可选的优化。订阅者索引的原理是:使用EventBus的注解处理器在应用构建期间创建订阅者索引类,该类已经包含了所有的订阅者信息。EventBus官方推荐在Android中使用订阅者索引以获得最佳的性能。

要开启订阅者索引的生成,你需要在构建脚本中使用annotationProcessor属性将EventBus的注解处理器添加到应用的构建中,还要设置一个eventBusIndex参数来指定要生成的订阅者索引的完全限定类名。

首先,修改模块下的build.gradle构建脚本。如下所示:

  1. android {
  2. defaultConfig {
  3. ...
  4. javaCompileOptions {
  5. annotationProcessorOptions {
  6. arguments = [eventBusIndex: 'com.github.cyc.eventbus.subscriberindexdemo.MyEventBusIndex']
  7. }
  8. }
  9. }
  10. ...
  11. }
  12. dependencies {
  13. ...
  14. compile 'org.greenrobot:eventbus:3.1.1'
  15. annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
  16. }
  17. 1
  18. 2
  19. 3
  20. 4
  21. 5
  22. 6
  23. 7
  24. 8
  25. 9
  26. 10
  27. 11
  28. 12
  29. 13
  30. 14
  31. 15
  32. 16
  33. 17

然后,build一下工程。EventBus注解处理器将为你生成一个订阅者索引类。示例代码如下所示:

  1. package com.github.cyc.eventbus.subscriberindexdemo;
  2. import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
  3. import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
  4. import org.greenrobot.eventbus.meta.SubscriberInfo;
  5. import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
  6. import org.greenrobot.eventbus.ThreadMode;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. /** This class is generated by EventBus, do not edit. */
  10. public class MyEventBusIndex implements SubscriberInfoIndex {
  11. private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;
  12. static {
  13. SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();
  14. putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
  15. new SubscriberMethodInfo("onMessageEvent", MessageEvent.class, ThreadMode.MAIN),
  16. }));
  17. }
  18. private static void putIndex(SubscriberInfo info) {
  19. SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
  20. }
  21. @Override
  22. public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
  23. SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
  24. if (info != null) {
  25. return info;
  26. } else {
  27. return null;
  28. }
  29. }
  30. }
  31. 1
  32. 2
  33. 3
  34. 4
  35. 5
  36. 6
  37. 7
  38. 8
  39. 9
  40. 10
  41. 11
  42. 12
  43. 13
  44. 14
  45. 15
  46. 16
  47. 17
  48. 18
  49. 19
  50. 20
  51. 21
  52. 22
  53. 23
  54. 24
  55. 25
  56. 26
  57. 27
  58. 28
  59. 29
  60. 30
  61. 31
  62. 32
  63. 33
  64. 34
  65. 35
  66. 36
  67. 37
  68. 38
  69. 39

可以看到,所有的订阅者信息都先被保存在SUBSCRIBER_INDEX静态成员变量中。后面查找订阅者信息时,EventBus就可以直接调用getSubscriberInfo()方法来获取该订阅者的信息了。

最后,在应用自定义的Application类的onCreate()方法中将订阅者索引添加到EventBus中,并将该EventBus设置成默认的EventBus。示例代码如下所示:

  1. public class MyApplication extends Application {
  2. @Override
  3. public void onCreate() {
  4. super.onCreate();
  5. // 配置EventBus
  6. EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
  7. }
  8. }
  9. 1
  10. 2
  11. 3
  12. 4
  13. 5
  14. 6
  15. 7
  16. 8
  17. 9

我们来看builder()、addIndex()和installDefaultEventBus()方法的代码:

  1. public class EventBus {
  2. static volatile EventBus defaultInstance;
  3. ...
  4. public static EventBusBuilder builder() {
  5. return new EventBusBuilder();
  6. }
  7. }
  8. public class EventBusBuilder {
  9. ...
  10. List<SubscriberInfoIndex> subscriberInfoIndexes;
  11. public EventBusBuilder addIndex(SubscriberInfoIndex index) {
  12. if (subscriberInfoIndexes == null) {
  13. subscriberInfoIndexes = new ArrayList<>();
  14. }
  15. subscriberInfoIndexes.add(index);
  16. return this;
  17. }
  18. public EventBus installDefaultEventBus() {
  19. synchronized (EventBus.class) {
  20. if (EventBus.defaultInstance != null) {
  21. throw new EventBusException("Default instance already exists." +
  22. " It may be only set once before it's used the first time to ensure consistent behavior.");
  23. }
  24. EventBus.defaultInstance = build();
  25. return EventBus.defaultInstance;
  26. }
  27. }
  28. public EventBus build() {
  29. return new EventBus(this);
  30. }
  31. }
  32. 1
  33. 2
  34. 3
  35. 4
  36. 5
  37. 6
  38. 7
  39. 8
  40. 9
  41. 10
  42. 11
  43. 12
  44. 13
  45. 14
  46. 15
  47. 16
  48. 17
  49. 18
  50. 19
  51. 20
  52. 21
  53. 22
  54. 23
  55. 24
  56. 25
  57. 26
  58. 27
  59. 28
  60. 29
  61. 30
  62. 31
  63. 32
  64. 33
  65. 34
  66. 35
  67. 36

builder()静态方法新建了一个EventBusBuilder对象。addIndex()方法将生成的订阅者索引添加到EventBusBuilder对象的subscriberInfoIndexes成员变量中。installDefaultEventBus()方法调用了build()方法新建了一个EventBus对象,并将该对象赋值给EventBus的defaultInstance静态成员变量。这样,后面调用EventBus.getDefault()静态方法获取到的就是该EventBus对象了。我们接着来看EventBus.getDefault()静态方法的代码:

  1. public class EventBus {
  2. static volatile EventBus defaultInstance;
  3. private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
  4. private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
  5. private final Map<Object, List<Class<?>>> typesBySubscriber;
  6. private final Map<Class<?>, Object> stickyEvents;
  7. private final Poster mainThreadPoster;
  8. private final BackgroundPoster backgroundPoster;
  9. private final AsyncPoster asyncPoster;
  10. private final SubscriberMethodFinder subscriberMethodFinder;
  11. ...
  12. public static EventBus getDefault() {
  13. if (defaultInstance == null) {
  14. synchronized (EventBus.class) {
  15. if (defaultInstance == null) {
  16. defaultInstance = new EventBus();
  17. }
  18. }
  19. }
  20. return defaultInstance;
  21. }
  22. public EventBus() {
  23. this(DEFAULT_BUILDER);
  24. }
  25. EventBus(EventBusBuilder builder) {
  26. logger = builder.getLogger();
  27. subscriptionsByEventType = new HashMap<>();
  28. typesBySubscriber = new HashMap<>();
  29. stickyEvents = new ConcurrentHashMap<>();
  30. mainThreadSupport = builder.getMainThreadSupport();
  31. mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
  32. backgroundPoster = new BackgroundPoster(this);
  33. asyncPoster = new AsyncPoster(this);
  34. indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
  35. subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
  36. builder.strictMethodVerification, builder.ignoreGeneratedIndex);
  37. logSubscriberExceptions = builder.logSubscriberExceptions;
  38. logNoSubscriberMessages = builder.logNoSubscriberMessages;
  39. sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
  40. sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
  41. throwSubscriberException = builder.throwSubscriberException;
  42. eventInheritance = builder.eventInheritance;
  43. executorService = builder.executorService;
  44. }
  45. }
  46. 1
  47. 2
  48. 3
  49. 4
  50. 5
  51. 6
  52. 7
  53. 8
  54. 9
  55. 10
  56. 11
  57. 12
  58. 13
  59. 14
  60. 15
  61. 16
  62. 17
  63. 18
  64. 19
  65. 20
  66. 21
  67. 22
  68. 23
  69. 24
  70. 25
  71. 26
  72. 27
  73. 28
  74. 29
  75. 30
  76. 31
  77. 32
  78. 33
  79. 34
  80. 35
  81. 36
  82. 37
  83. 38
  84. 39
  85. 40
  86. 41
  87. 42
  88. 43
  89. 44
  90. 45
  91. 46
  92. 47
  93. 48
  94. 49
  95. 50
  96. 51

getDefault()静态方法使用了单例模式,保证只有一个默认的EventBus实例。EventBus实例的创建使用了建造者模式。无论是调用了installDefaultEventBus()方法,还是只调用了getDefault()静态方法,最终都调用了EventBus(EventBusBuilder builder)构造方法来创建EventBus实例。EventBus()构造方法主要是初始化了一些数据结构和复制了EventBusBuilder对象的配置值:

  • subscriptionsByEventType成员变量以事件类型的Class对象为键,用于保存订阅了该事件类型的所有的订阅者信息。
  • typesBySubscriber成员变量以订阅者对象为键,用于保存该订阅者订阅的所有的事件类型。
  • stickyEvents成员变量以事件类型的Class对象为键,用于保存该事件类型最近一次发布的粘性事件。
  • mainThreadPoster成员变量用于ThreadMode.MAIN和ThreadMode.MAIN_ORDERED线程模式下事件的传递。
  • backgroundPoster成员变量用于ThreadMode.BACKGROUND线程模式下事件的传递。
  • asyncPoster成员变量用于ThreadMode.ASYNC线程模式下事件的传递。
  • subscriberMethodFinder成员变量用于查找订阅者方法。它保存了EventBusBuilder对象的subscriberInfoIndexes成员变量,也就是订阅者索引。

订阅事件

订阅事件主要分为两个过程:

  1. 注册订阅者
  2. 注销订阅者

调用register()方法可以注册一个订阅者。我们先来看register()方法的代码:

  1. public class EventBus {
  2. public void register(Object subscriber) {
  3. Class<?> subscriberClass = subscriber.getClass();
  4. List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
  5. synchronized (this) {
  6. for (SubscriberMethod subscriberMethod : subscriberMethods) {
  7. subscribe(subscriber, subscriberMethod);
  8. }
  9. }
  10. }
  11. ...
  12. }
  13. 1
  14. 2
  15. 3
  16. 4
  17. 5
  18. 6
  19. 7
  20. 8
  21. 9
  22. 10
  23. 11
  24. 12
  25. 13

register()方法先调用了subscriberMethodFinder成员变量的findSubscriberMethods()方法来查找该订阅者的订阅者方法,然后才调用subscribe()方法开始注册订阅者。所以,我们先来分析一下查找订阅者方法的过程。

查找订阅者方法

我们来看findSubscriberMethods()方法的代码:

  1. class SubscriberMethodFinder {
  2. ...
  3. private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
  4. List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
  5. List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
  6. if (subscriberMethods != null) {
  7. return subscriberMethods;
  8. }
  9. if (ignoreGeneratedIndex) {
  10. subscriberMethods = findUsingReflection(subscriberClass);
  11. } else {
  12. subscriberMethods = findUsingInfo(subscriberClass);
  13. }
  14. if (subscriberMethods.isEmpty()) {
  15. throw new EventBusException("Subscriber " + subscriberClass
  16. + " and its super classes have no public methods with the @Subscribe annotation");
  17. } else {
  18. METHOD_CACHE.put(subscriberClass, subscriberMethods);
  19. return subscriberMethods;
  20. }
  21. }
  22. private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
  23. FindState findState = prepareFindState();
  24. findState.initForSubscriber(subscriberClass);
  25. while (findState.clazz != null) {
  26. findUsingReflectionInSingleClass(findState);
  27. findState.moveToSuperclass();
  28. }
  29. return getMethodsAndRelease(findState);
  30. }
  31. }
  32. 1
  33. 2
  34. 3
  35. 4
  36. 5
  37. 6
  38. 7
  39. 8
  40. 9
  41. 10
  42. 11
  43. 12
  44. 13
  45. 14
  46. 15
  47. 16
  48. 17
  49. 18
  50. 19
  51. 20
  52. 21
  53. 22
  54. 23
  55. 24
  56. 25
  57. 26
  58. 27
  59. 28
  60. 29
  61. 30
  62. 31
  63. 32
  64. 33
  65. 34

findSubscriberMethods()方法先从METHOD_CACHE缓存中获取订阅者方法。如果获取到了订阅者方法,那么直接返回。反之,开始查找订阅者的订阅者方法。ignoreGeneratedIndex成员变量表示是否忽略生成的订阅者索引,它来自EventBusBuilder对象的ignoreGeneratedIndex成员变量,默认值为false,表示不忽略。因此,默认情况下,将调用findUsingInfo()方法来查找订阅者方法。如果用户没有生成或者添加订阅者索引的话,那么findUsingInfo()方法将与findUsingReflection()方法一样最终调用findUsingReflectionInSingleClass()方法使用Java反射来查找订阅者方法。如果没有查找到订阅者方法,那么将抛出EventBusException异常。反之,先更新METHOD_CACHE缓存,然后再返回。我们接着来看findUsingInfo()方法的代码:

  1. class SubscriberMethodFinder {
  2. private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
  3. FindState findState = prepareFindState();
  4. findState.initForSubscriber(subscriberClass);
  5. while (findState.clazz != null) {
  6. findState.subscriberInfo = getSubscriberInfo(findState);
  7. if (findState.subscriberInfo != null) {
  8. SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
  9. for (SubscriberMethod subscriberMethod : array) {
  10. if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
  11. findState.subscriberMethods.add(subscriberMethod);
  12. }
  13. }
  14. } else {
  15. findUsingReflectionInSingleClass(findState);
  16. }
  17. findState.moveToSuperclass();
  18. }
  19. return getMethodsAndRelease(findState);
  20. }
  21. private SubscriberInfo getSubscriberInfo(FindState findState) {
  22. if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
  23. SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
  24. if (findState.clazz == superclassInfo.getSubscriberClass()) {
  25. return superclassInfo;
  26. }
  27. }
  28. if (subscriberInfoIndexes != null) {
  29. for (SubscriberInfoIndex index : subscriberInfoIndexes) {
  30. SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
  31. if (info != null) {
  32. return info;
  33. }
  34. }
  35. }
  36. return null;
  37. }
  38. ...
  39. }
  40. 1
  41. 2
  42. 3
  43. 4
  44. 5
  45. 6
  46. 7
  47. 8
  48. 9
  49. 10
  50. 11
  51. 12
  52. 13
  53. 14
  54. 15
  55. 16
  56. 17
  57. 18
  58. 19
  59. 20
  60. 21
  61. 22
  62. 23
  63. 24
  64. 25
  65. 26
  66. 27
  67. 28
  68. 29
  69. 30
  70. 31
  71. 32
  72. 33
  73. 34
  74. 35
  75. 36
  76. 37
  77. 38
  78. 39
  79. 40
  80. 41

findUsingInfo()方法使用了while循环,不仅查找了订阅者的订阅者方法,而且查找了订阅者父类的订阅者方法。findUsingInfo()方法先调用了getSubscriberInfo()方法来获取订阅者信息。如果生成并添加了订阅者索引,即subscriberInfoIndexes成员变量不为null,那么getSubscriberInfo()方法将遍历subscriberInfoIndexes成员变量来查找订阅者信息。如果获取到了订阅者信息,那么将订阅者信息里的订阅者方法保存起来。反之,调用findUsingReflectionInSingleClass()方法来查找订阅者方法。我们接着来看findUsingReflectionInSingleClass()方法的代码:

  1. class SubscriberMethodFinder {
  2. private void findUsingReflectionInSingleClass(FindState findState) {
  3. Method[] methods;
  4. try {
  5. // This is faster than getMethods, especially when subscribers are fat classes like Activities
  6. methods = findState.clazz.getDeclaredMethods();
  7. } catch (Throwable th) {
  8. // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
  9. methods = findState.clazz.getMethods();
  10. findState.skipSuperClasses = true;
  11. }
  12. for (Method method : methods) {
  13. int modifiers = method.getModifiers();
  14. if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
  15. Class<?>[] parameterTypes = method.getParameterTypes();
  16. if (parameterTypes.length == 1) {
  17. Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
  18. if (subscribeAnnotation != null) {
  19. Class<?> eventType = parameterTypes[0];
  20. if (findState.checkAdd(method, eventType)) {
  21. ThreadMode threadMode = subscribeAnnotation.threadMode();
  22. findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
  23. subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
  24. }
  25. }
  26. } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
  27. String methodName = method.getDeclaringClass().getName() + "." + method.getName();
  28. throw new EventBusException("@Subscribe method " + methodName +
  29. "must have exactly 1 parameter but has " + parameterTypes.length);
  30. }
  31. } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
  32. String methodName = method.getDeclaringClass().getName() + "." + method.getName();
  33. throw new EventBusException(methodName +
  34. " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
  35. }
  36. }
  37. }
  38. ...
  39. }
  40. 1
  41. 2
  42. 3
  43. 4
  44. 5
  45. 6
  46. 7
  47. 8
  48. 9
  49. 10
  50. 11
  51. 12
  52. 13
  53. 14
  54. 15
  55. 16
  56. 17
  57. 18
  58. 19
  59. 20
  60. 21
  61. 22
  62. 23
  63. 24
  64. 25
  65. 26
  66. 27
  67. 28
  68. 29
  69. 30
  70. 31
  71. 32
  72. 33
  73. 34
  74. 35
  75. 36
  76. 37
  77. 38
  78. 39
  79. 40

findUsingReflectionInSingleClass()方法使用了Java反射来查找订阅者方法。只有那些同时满足public访问权限、非static方法、非abstract方法、有且只有一个参数和使用了@Subscribe注解的方法才被当做是合法的订阅者方法。

注册订阅者

register()方法在查找到订阅者所有的订阅者方法之后,遍历订阅者方法为每个订阅者方法调用了subscribe()方法。我们接着来看subscribe()方法的代码:

  1. public class EventBus {
  2. private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
  3. Class<?> eventType = subscriberMethod.eventType;
  4. Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
  5. CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
  6. if (subscriptions == null) {
  7. subscriptions = new CopyOnWriteArrayList<>();
  8. subscriptionsByEventType.put(eventType, subscriptions);
  9. } else {
  10. if (subscriptions.contains(newSubscription)) {
  11. throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
  12. + eventType);
  13. }
  14. }
  15. int size = subscriptions.size();
  16. for (int i = 0; i <= size; i++) {
  17. if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
  18. subscriptions.add(i, newSubscription);
  19. break;
  20. }
  21. }
  22. List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
  23. if (subscribedEvents == null) {
  24. subscribedEvents = new ArrayList<>();
  25. typesBySubscriber.put(subscriber, subscribedEvents);
  26. }
  27. subscribedEvents.add(eventType);
  28. if (subscriberMethod.sticky) {
  29. if (eventInheritance) {
  30. // Existing sticky events of all subclasses of eventType have to be considered.
  31. // Note: Iterating over all events may be inefficient with lots of sticky events,
  32. // thus data structure should be changed to allow a more efficient lookup
  33. // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
  34. Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
  35. for (Map.Entry<Class<?>, Object> entry : entries) {
  36. Class<?> candidateEventType = entry.getKey();
  37. if (eventType.isAssignableFrom(candidateEventType)) {
  38. Object stickyEvent = entry.getValue();
  39. checkPostStickyEventToSubscription(newSubscription, stickyEvent);
  40. }
  41. }
  42. } else {
  43. Object stickyEvent = stickyEvents.get(eventType);
  44. checkPostStickyEventToSubscription(newSubscription, stickyEvent);
  45. }
  46. }
  47. }
  48. ...
  49. }
  50. 1
  51. 2
  52. 3
  53. 4
  54. 5
  55. 6
  56. 7
  57. 8
  58. 9
  59. 10
  60. 11
  61. 12
  62. 13
  63. 14
  64. 15
  65. 16
  66. 17
  67. 18
  68. 19
  69. 20
  70. 21
  71. 22
  72. 23
  73. 24
  74. 25
  75. 26
  76. 27
  77. 28
  78. 29
  79. 30
  80. 31
  81. 32
  82. 33
  83. 34
  84. 35
  85. 36
  86. 37
  87. 38
  88. 39
  89. 40
  90. 41
  91. 42
  92. 43
  93. 44
  94. 45
  95. 46
  96. 47
  97. 48
  98. 49
  99. 50
  100. 51
  101. 52
  102. 53

首先,subscribe()方法创建了一个包含了该订阅者方法和对应订阅者的Subscription对象,并根据订阅者方法的事件传递优先级将该Subscription对象添加到对应事件类型的Subscription列表中。然后,将该订阅者方法对应的事件类型添加到对应订阅者的订阅事件类型列表中。最后,如果是订阅了粘性事件的订阅者方法,那么会先获取对应事件类型的粘性事件并最终调用postToSubscription()方法将该粘性事件发送给订阅者。

注销订阅者

调用unregister()方法可以注销一个订阅者。我们接着来看unregister()方法的代码:

  1. public class EventBus {
  2. public synchronized void unregister(Object subscriber) {
  3. List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
  4. if (subscribedTypes != null) {
  5. for (Class<?> eventType : subscribedTypes) {
  6. unsubscribeByEventType(subscriber, eventType);
  7. }
  8. typesBySubscriber.remove(subscriber);
  9. } else {
  10. logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
  11. }
  12. }
  13. private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
  14. List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
  15. if (subscriptions != null) {
  16. int size = subscriptions.size();
  17. for (int i = 0; i < size; i++) {
  18. Subscription subscription = subscriptions.get(i);
  19. if (subscription.subscriber == subscriber) {
  20. subscription.active = false;
  21. subscriptions.remove(i);
  22. i--;
  23. size--;
  24. }
  25. }
  26. }
  27. }
  28. ...
  29. }
  30. 1
  31. 2
  32. 3
  33. 4
  34. 5
  35. 6
  36. 7
  37. 8
  38. 9
  39. 10
  40. 11
  41. 12
  42. 13
  43. 14
  44. 15
  45. 16
  46. 17
  47. 18
  48. 19
  49. 20
  50. 21
  51. 22
  52. 23
  53. 24
  54. 25
  55. 26
  56. 27
  57. 28
  58. 29
  59. 30
  60. 31

首先,unregister()方法获取了该订阅者订阅的所有的事件类型列表。然后,遍历事件类型列表对每个事件类型调用unsubscribeByEventType()方法。unsubscribeByEventType()方法先获取订阅了该事件类型的所有的Subscription列表,然后从列表中删除了与该订阅者相关的Subscription对象。最后,从typesBySubscriber成员变量中删除了该订阅者订阅的所有的事件类型列表。

发布事件

调用post()方法可以发布一个事件。我们接着来看post()方法的代码:

  1. public class EventBus {
  2. public void post(Object event) {
  3. PostingThreadState postingState = currentPostingThreadState.get();
  4. List<Object> eventQueue = postingState.eventQueue;
  5. eventQueue.add(event);
  6. if (!postingState.isPosting) {
  7. postingState.isMainThread = isMainThread();
  8. postingState.isPosting = true;
  9. if (postingState.canceled) {
  10. throw new EventBusException("Internal error. Abort state was not reset");
  11. }
  12. try {
  13. while (!eventQueue.isEmpty()) {
  14. postSingleEvent(eventQueue.remove(0), postingState);
  15. }
  16. } finally {
  17. postingState.isPosting = false;
  18. postingState.isMainThread = false;
  19. }
  20. }
  21. }
  22. ...
  23. }
  24. 1
  25. 2
  26. 3
  27. 4
  28. 5
  29. 6
  30. 7
  31. 8
  32. 9
  33. 10
  34. 11
  35. 12
  36. 13
  37. 14
  38. 15
  39. 16
  40. 17
  41. 18
  42. 19
  43. 20
  44. 21
  45. 22
  46. 23
  47. 24
  48. 25

post()方法先将事件添加到当前线程的PostingThreadState对象的事件队列的末尾。最终调用了postSingleEvent()方法将事件发布出去。我们接着来看postSingleEvent()方法的代码:

  1. public class EventBus {
  2. private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
  3. Class<?> eventClass = event.getClass();
  4. boolean subscriptionFound = false;
  5. if (eventInheritance) {
  6. List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
  7. int countTypes = eventTypes.size();
  8. for (int h = 0; h < countTypes; h++) {
  9. Class<?> clazz = eventTypes.get(h);
  10. subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
  11. }
  12. } else {
  13. subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
  14. }
  15. if (!subscriptionFound) {
  16. if (logNoSubscriberMessages) {
  17. logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
  18. }
  19. if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
  20. eventClass != SubscriberExceptionEvent.class) {
  21. post(new NoSubscriberEvent(this, event));
  22. }
  23. }
  24. }
  25. private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
  26. CopyOnWriteArrayList<Subscription> subscriptions;
  27. synchronized (this) {
  28. subscriptions = subscriptionsByEventType.get(eventClass);
  29. }
  30. if (subscriptions != null && !subscriptions.isEmpty()) {
  31. for (Subscription subscription : subscriptions) {
  32. postingState.event = event;
  33. postingState.subscription = subscription;
  34. boolean aborted = false;
  35. try {
  36. postToSubscription(subscription, event, postingState.isMainThread);
  37. aborted = postingState.canceled;
  38. } finally {
  39. postingState.event = null;
  40. postingState.subscription = null;
  41. postingState.canceled = false;
  42. }
  43. if (aborted) {
  44. break;
  45. }
  46. }
  47. return true;
  48. }
  49. return false;
  50. }
  51. ...
  52. }
  53. 1
  54. 2
  55. 3
  56. 4
  57. 5
  58. 6
  59. 7
  60. 8
  61. 9
  62. 10
  63. 11
  64. 12
  65. 13
  66. 14
  67. 15
  68. 16
  69. 17
  70. 18
  71. 19
  72. 20
  73. 21
  74. 22
  75. 23
  76. 24
  77. 25
  78. 26
  79. 27
  80. 28
  81. 29
  82. 30
  83. 31
  84. 32
  85. 33
  86. 34
  87. 35
  88. 36
  89. 37
  90. 38
  91. 39
  92. 40
  93. 41
  94. 42
  95. 43
  96. 44
  97. 45
  98. 46
  99. 47
  100. 48
  101. 49
  102. 50
  103. 51
  104. 52
  105. 53
  106. 54

eventInheritance成员变量表示是否需要考虑事件的继承,即是否要发布对应事件类型的父类型的事件。它来自EventBusBuilder对象的eventInheritance成员变量,默认值为true,表示需要考虑事件的继承。因此,默认情况下,postSingleEvent()方法不仅调用了postSingleEventForEventType()方法发布了对应事件类型的事件,而且发布了对应事件类型的父类型的事件。postSingleEventForEventType()方法先获取订阅了该事件类型的所有的Subscription列表。然后遍历Subscription列表对每个Subscription对象调用了postToSubscription()方法将事件发布出去。我们接着来看postToSubscription()方法的代码:

  1. public class EventBus {
  2. private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
  3. switch (subscription.subscriberMethod.threadMode) {
  4. case POSTING:
  5. invokeSubscriber(subscription, event);
  6. break;
  7. case MAIN:
  8. if (isMainThread) {
  9. invokeSubscriber(subscription, event);
  10. } else {
  11. mainThreadPoster.enqueue(subscription, event);
  12. }
  13. break;
  14. case MAIN_ORDERED:
  15. if (mainThreadPoster != null) {
  16. mainThreadPoster.enqueue(subscription, event);
  17. } else {
  18. // temporary: technically not correct as poster not decoupled from subscriber
  19. invokeSubscriber(subscription, event);
  20. }
  21. break;
  22. case BACKGROUND:
  23. if (isMainThread) {
  24. backgroundPoster.enqueue(subscription, event);
  25. } else {
  26. invokeSubscriber(subscription, event);
  27. }
  28. break;
  29. case ASYNC:
  30. asyncPoster.enqueue(subscription, event);
  31. break;
  32. default:
  33. throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
  34. }
  35. }
  36. void invokeSubscriber(Subscription subscription, Object event) {
  37. try {
  38. subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
  39. } catch (InvocationTargetException e) {
  40. handleSubscriberException(subscription, event, e.getCause());
  41. } catch (IllegalAccessException e) {
  42. throw new IllegalStateException("Unexpected exception", e);
  43. }
  44. }
  45. ...
  46. }
  47. 1
  48. 2
  49. 3
  50. 4
  51. 5
  52. 6
  53. 7
  54. 8
  55. 9
  56. 10
  57. 11
  58. 12
  59. 13
  60. 14
  61. 15
  62. 16
  63. 17
  64. 18
  65. 19
  66. 20
  67. 21
  68. 22
  69. 23
  70. 24
  71. 25
  72. 26
  73. 27
  74. 28
  75. 29
  76. 30
  77. 31
  78. 32
  79. 33
  80. 34
  81. 35
  82. 36
  83. 37
  84. 38
  85. 39
  86. 40
  87. 41
  88. 42
  89. 43
  90. 44
  91. 45
  92. 46
  93. 47
  94. 48

postToSubscription()方法针对每一种线程模式使用了对应的发布事件策略:

  • ThreadMode.POSTING。在当前发布事件的线程中直接调用订阅者方法。
  • ThreadMode.MAIN。如果当前线程就是主线程,那么直接调用订阅者方法。反之,先进入队列,后面将在主线程的Handler中调用订阅者方法。
  • ThreadMode.MAIN_ORDERED。直接进入队列,后面将在主线程的Handler中调用订阅者方法。
  • ThreadMode.BACKGROUND。如果当前线程不是主线程,那么直接调用订阅者方法。反之,先进入队列,后面将在线程池的工作线程中调用订阅者方法。
  • ThreadMode.ASYNC。直接进入队列,后面将在线程池的工作线程中调用订阅者方法。

以上调用订阅者方法都是通过调用invokeSubscriber()方法以Java反射的方式调用的。

总结

EventBus是一种用于Android的发布/订阅事件总线。使用EventBus可以简化应用组件间的通信,可以解耦事件的发送者和接收者。

参考

  • EventBus 3.1.1
  • http://greenrobot.org/eventbus/
  • https://github.com/greenrobot/EventBus

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读

    相关 EventBus分析

    前言 EventBus是一种用于Android的发布/订阅事件总线。它有很多优点:简化应用组件间的通信;解耦事件的发送者和接收者;避免复杂和容易出错的依赖和生命周期的问题

    相关 Android EventBus解析

    EventBus概述和优点 1.Android事件发布、订阅框架 2.事件传递可用于Android四大组件间通讯 3.简洁,使用简单,并将事件的发布和订阅充分解耦