EventBus 实现原理

EventBus 是 Android 中比较常用的第三方控件了,具体使用就不写了,分析一下源码实现。

EventBus 的主要实现机制还是基于反射,一句话概括就是:

  1. 注册时传入目标类对象,然后利用反射筛选出 @Subscribe 的方法,然后以相同的参数类型为 key,将不同的方法合并为 list 作为 value,得到一个 map 集合;
  2. 当用户 post 数据时,再以数据类型为 key,从 map 中取出对应的方法 list,然后遍历 list,再利用反射机制对指定的方法执行 invoke 操作,完成调用;

EventBus#register

下面开始过源码,先从注册开始:

 public void register(Object subscriber) {
   Class subscriberClass = subscriber.getClass();
   // 第一步,找到注解方法
   List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
   synchronized (this) {
     // 第二部,循环遍历注解方法,进行订阅绑定
     for (SubscriberMethod subscriberMethod : subscriberMethods) {
       subscribe(subscriber, subscriberMethod);
     }
   }
}

第一步,找到注解方法

下面假设 register 方法传入的是 MainActivity.this,方便理解。

所以很明显,subscriber.getClass() 得到的就是MainActivity 对象,然后进入 findSubscriberMethods 方法。

List findSubscriberMethods(Class subscriberClass) {
    // METHOD_CACHE,缓存 Map,key:当前类,value:类的订阅方法
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
      return subscriberMethods;
    }

    if (ignoreGeneratedIndex) { // 默认为 false
      subscriberMethods = findUsingReflection(subscriberClass);
    } else {
      subscriberMethods = findUsingInfo(subscriberClass);
    }
  
}

// findUsingReflectionInSingleClass
private List findUsingInfo(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
      // 利用反射机制找到目标方法
      findUsingReflectionInSingleClass(findState);
      // 处理完当前类以后再去父类看看
      findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

下面就来到了核心方法:findUsingReflectionInSingleClass

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
      // 根据目标类对象,找到所有方法
      methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
      methods = findState.clazz.getMethods();
      findState.skipSuperClasses = true;
    }
    // 遍历方法集
    for (Method method : methods) {
      int modifiers = method.getModifiers();
      // @Subscribe method: must be public, non-static, and non-abstract
      if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
        Class[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 1) {
          // 必须只有一个参数
          Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
          // 拿到 @Subscribe 注解属性
          if (subscribeAnnotation != null) {
            Class eventType = parameterTypes[0];
            if (findState.checkAdd(method, eventType)) {
              // 解析注解属性,即 threadMode, priority, sticky 等,eventType 是方法参数类型
              ThreadMode threadMode = subscribeAnnotation.threadMode();
              // 重新构建一个 SubscriberMethod 对象,添加到 subscriberMethods 集合中
              findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode, subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
            }
          }
        } 
      } 
    }
}

代码走到这里,就完成了第一步的筛选工作:将目标类中所有的 @Subscribe 方法筛选出来,并将其注解属性、参数类型等信息重新包装成 SubscriberMethod 对象,存储到集合中返回。

第二步,订阅绑定

synchronized (this) {
  for (SubscriberMethod subscriberMethod : subscriberMethods) {
    subscribe(subscriber, subscriberMethod);
  }
}

很明显,接下来的重点在 subscribe 方法:

// 以「参数类型」为 key,「Subscription 集合」为 value 的 map 数据集
private final Map, CopyOnWriteArrayList> subscriptionsByEventType;

// 以「目标类对象」为 key,「注册方法参数类集合」为 value 的 map 数据集
private final Map>> typesBySubscriber;

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
  // 注册方法的参数类型,是 map 集合的 key
  Class eventType = subscriberMethod.eventType; 
  // 以目标类(MainActivity)和注解订阅方法重新构建新对象 Subscription
  Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
  // 以 key 值去取出对应的 list 对象
  CopyOnWriteArrayList subscriptions =subscriptionsByEventType.get(eventType);
  if (subscriptions == null) {
    // 如果为空,就初始化数据,然后将数据 put 进去
    subscriptions = new CopyOnWriteArrayList<>();
    subscriptionsByEventType.put(eventType, subscriptions);
  } 

  // 根据 priority 对集合重新进行排序 
  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;
    }
  }

  // 主要用于解注册,与业务无关
  // 根据当前类对象(MainActivity)从 map 中获取集合数据
  List> subscribedEvents = typesBySubscriber.get(subscriber);
  if (subscribedEvents == null) {
    // 如果为空,就初始化集合,然后将 key-value 存入
    subscribedEvents = new ArrayList<>();
    typesBySubscriber.put(subscriber, subscribedEvents);
  }
  // 将当前方法的参数类型存入集合
  subscribedEvents.add(eventType);

  // 如果是粘性事件
  if (subscriberMethod.sticky) {
    if (eventInheritance) { // 默认为 true
      Set, Object>> entries = stickyEvents.entrySet();
      for (Map.Entry, Object> entry : entries) {
        Class candidateEventType = entry.getKey();
        if (eventType.isAssignableFrom(candidateEventType)) {
          Object stickyEvent = entry.getValue();
                // 则会在注册的时候调用注册方法(粘性事件 post 发生在注册以前)
          checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
      }
    } else {
      Object stickyEvent = stickyEvents.get(eventType);
      checkPostStickyEventToSubscription(newSubscription, stickyEvent);
    }
  }
}

整个 EventBus 的注册流程大概就是这样。相对应的,解注册流程就很简单了,只是做了一些常规的清空数据,消除引用,从而避免内存泄漏的操作,就不再具体分析了。

public synchronized void unregister(Object subscriber) {
    // 根据订阅类对象取出当前类中所有的注解方法属性集合 Class -> List
    List> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
      // 遍历循环,对当前类进行解注册
      for (Class eventType : subscribedTypes) {
        unsubscribeByEventType(subscriber, eventType);
      }
      // 将当前类移除
      typesBySubscriber.remove(subscriber);
    } 
}

private void unsubscribeByEventType(Object subscriber, Class eventType) {
  // 根据指定的参数类型,从 map 中取出包含(注册类,注解属性)的 list 集合
  List subscriptions = subscriptionsByEventType.get(eventType);
  if (subscriptions != null) {
    int size = subscriptions.size();
    for (int i = 0; i < size; i++) {
      // 遍历 list,与注册类进行匹配
      Subscription subscription = subscriptions.get(i);
      if (subscription.subscriber == subscriber) {
        subscription.active = false;
        // 找到匹配的数据后,将其从 list 移除,避免内存泄漏
        subscriptions.remove(i);
        i--;
        size--;
      }
    }
  }
}

EventBus#post

说完了注册和解注册,下面来说说 post 动作。post 动作说也简单,实际上就是 method.invoke 的过程。

1. 将事件入队

public void post(Object event) {
  // 维护一个事件发送的状态
  PostingThreadState postingState = currentPostingThreadState.get();
  List 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;
    }
  }
}
 
 

2.根据 Event 数据类型,获取它和它的父类以及接口类

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
  Class eventClass = event.getClass();
  boolean subscriptionFound = false;
  if (eventInheritance) { // 默认为 true
    // 根据 post 的数据类型,拿到当前类型及其父类、接口等所有相关的类型,存入集合中
    List> eventTypes = lookupAllEventTypes(eventClass);
    int countTypes = eventTypes.size();
    for (int h = 0; h < countTypes; h++) {
      Class clazz = eventTypes.get(h);
      // 遍历 Event Class or interface
      subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
    }
  } else {
    subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
  }
}

3. 遍历 Event 类集合,EventBus 所有的订阅事件都是已 Event 类为 key 存储的

private boolean postSingleEventForEventType(Object event, 
                                            PostingThreadState postingState, 
                                            Class eventClass) {
  CopyOnWriteArrayList subscriptions;
  synchronized (this) {
    // 根据当前 Event 类型,从 map 中拿到包含了(注册类、注解属性)的集合数据
    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;
}

// 区分不同的 threadMode
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 MAIN_ORDERED:
      if (mainThreadPoster != null) {
        mainThreadPoster.enqueue(subscription, event);
      } else {
        invokeSubscriber(subscription, event);
      }
      break;
    case BACKGROUND:
      if (isMainThread) {
        backgroundPoster.enqueue(subscription, event);
      } else {
        invokeSubscriber(subscription, event);
      }
      break;
    case ASYNC:
      asyncPoster.enqueue(subscription, event);
      break;
  }
}

// 反射调用
void invokeSubscriber(Subscription subscription, Object event) {
  try {
    subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
  } 
}

总结

整个 EventBus 流程大体就是这样。

简单总结一下,我们在注册流程中分析过,EventBus 是以发送的 Event 事件的 class 类型为 key 值,对不同订阅者、不同订阅方法进行封装、归并,再作为 value 存储起来的。

具体像是这样:

EventClass -> List

举例来说,

如果有三个类注册了 EventBus,分别是:FirstActivity,SecondActivity,ThirdActivity;然后它们三个又分别声明了一个传递 String 类型 Event 的方法:

// FirstActivity
@Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
public void testFirst(String data) {
  Log.e("TAG", "testFirst = " + data);
}

// SecondActivity
@Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
public void testSecond(String data) {
  Log.e("TAG", "testSecond = " + data);
}

// ThirdActivity
@Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
public void testThird(String data) {
  Log.e("TAG", "testSecond = " + data);
}

那么,当 EventBus#register 走完之后,你应该得到一个这样的 map 集合:

image.png

等到在某个地方 post 一个 String 数据时:

Event.getDefault().post("This is a String event");

代码会在处理一系列逻辑后,来到 postSingleEventForEventType() 中:

// 根据当前 Event 类型,从 map 中拿到包含了(注册类、注解属性)的集合数据
subscriptions = subscriptionsByEventType.get(eventClass);

然后根据 String.class,从 map 中取出对应的集合,再次进行遍历,然后依次调用 invoke 方法,完成数据的传递:

// 如
// subscription.subscriberMethod 就是上边的 testFirst()
// subscription.subscriber 就是对应的 FirstActivity.this
// event 就是传递过来的 “This is a String event”
// 然后使用反射的方式调用该方法,完成调用
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);

你可能感兴趣的:(EventBus 实现原理)