EventBus 3.1.1 自己对源码的理解

一:使用步骤

1、eventbus3.1.1版本依赖:

   implementation 'org.greenrobot:eventbus:3.1.1'

2、在 Activity 或 Fragment 中进行注册:

  EventBus.getDefault().register(this);

3、在注册的 Activity 或 Fragment 中进行接收,需要写一个接收方法:

3.1 、注解上使用默认参数接收方法

  @Subscribe
  public void receive(String data) {
    // TODO: Create by Ysw 2019/7/18 进行相关 data 的数据处理
  }

3.2、注解上进行自定义参数值接收方法

  @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
  public void receive(Object data) {
     // TODO: Create by Ysw 2019/7/18 进行相关 data 的数据处理
  }

4、在注册 EventBus 的 Activity 或 Fragment 的 onDestroy 生命周期方法中进行注销

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

5、在需要发出通知的地方进行调用,可以是 Fragment Activity 或者别的工具类中,EventBus 目前不支持跨进程通讯,需保持在同一个进程中进行一个完整的操作。

  private void sendMessage(){
    EventBus.getDefault().post("这个是我发的测试消息");
    EventBus.getDefault().post(new Friend("Ysw",18));
  }

二:我们从注册开始着手解析。

我们进入 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 方法中做了三件事,第一通过反射拿到 class 对象,二,通过这个 class 对象去遍历这个类里面的方法并返回一个呗 @Subscribe 所注释了的方法集合。三,对这个方法集合进行遍历并做相应的操作。

我们来看他是怎么进行类里面方法遍历并返回相关方法集合的,我们进入到 subscriberMethodFinder 中的subscriberMethodFinder() 方法:

     // 这是一个 Map 容器,key 值是一个 class 类,value 是一个方法集合
    private static final Map, List> METHOD_CACHE = new ConcurrentHashMap<>();

    List findSubscriberMethods(Class subscriberClass) {
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    // 第一次进来,容器肯定为空,找不到相关的 方法集合
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    // ignoreGeneratedIndex 默认值是 false
    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;
    }
}

进入 findUsingInfo(Class subscriberClass) 方法:

   private List findUsingInfo(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        // findState.subscriberInfo 没有进行赋值,进入 findUsingReflectionInSingleClass(findState) 方法
        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);
}

findUsingReflectionInSingleClass(findState) 方法

   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;
    }
    // 遍历这个集合,获取被 Subscribe 所注释的方法并添加到 subscriberMethods 中
    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");
        }
    }
}

getMethodsAndRelease(FindState findState) 方法 直接将 findState.subscriberMethods 方法集合返回

  private List getMethodsAndRelease(FindState findState) {
    List subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    findState.recycle();
    synchronized (FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (FIND_STATE_POOL[i] == null) {
                FIND_STATE_POOL[i] = findState;
                break;
            }
        }
    }
    return subscriberMethods;
}

最后将 subscriberMethods 添加到 METHOD_CACHE map容器中并返回

   List findSubscriberMethods(Class subscriberClass) {
       //   代码省略
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
      //   代码省略
}

回到 EventBus 的 subscribe(subscriber, subscriberMethod) 方法

     private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
          Class eventType = subscriberMethod.eventType;
          Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
          CopyOnWriteArrayList 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> 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).
                  Set, Object>> entries = stickyEvents.entrySet();
                  for (Map.Entry, 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);
              }
          }
      }

在subscriptionsByEventType去查找一个CopyOnWriteArrayList ,如果没有则创建一个新的CopyOnWriteArrayList;
然后将这个CopyOnWriteArrayList放入subscriptionsByEventType中,这里的subscriptionsByEventType是一个Map,key为eventType,value为CopyOnWriteArrayList,这个Map非常重要,后续还会用到它;
接下来,就是添加newSubscription,它属于Subscription类,里面包含着subscriber和subscriberMethod等信息,同时这里有一个优先级的判断,说明它是按照优先级添加的。优先级越高,会插到在当前List靠前面的位置;
typesBySubscriber这个类也是一个Map,key为subscriber,value为subscribedEvents,即所有的eventType列表,这个类我找了一下,发现在EventBus#isRegister()方法中有用到,应该是用来判断这个Subscriber是否已被注册过。然后将当前的eventType添加到subscribedEvents中;
最后,判断是否是sticky。如果是sticky事件的话,到最后会调用checkPostStickyEventToSubscription()方法。

  private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
    if (stickyEvent != null) {
        // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
        // --> Strange corner case, which we don't take care of here.
        postToSubscription(newSubscription, stickyEvent, isMainThread());
    }
}

接着看是如何让发送消息的,post() 方法

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

进入 postSingleEvent(eventQueue.remove(0), postingState)方法

   private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        List> 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()方法

   private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList subscriptions;
    synchronized (this) {
        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;
}

最后调用 postToSubscription() 方法

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

最后根据线程类别进行调用
POSTING:执行invokeSubscriber()方法,就是直接反射调用
MAIN:首先去判断当前是否在UI线程,如果是的话则直接反射调用,否则调用mainThreadPoster#enqueue(),即把当前的方法加入到队列之中,然后通过handler去发送一个消息,在handler的handleMessage中去执行方法。具体逻辑在HandlerPoster.java中;
MAIN_ORDERED:与上面逻辑类似,顺序执行我们的方法。
BACKGROUND:判断当前是否在UI线程,如果不是的话直接反射调用,是的话通过。backgroundPoster.enqueue()将方法加入到后台的一个队列,最后通过线程池去执行。
ASYNC:与BACKGROUND的逻辑类似,将任务加入到后台的一个队列,最终由Eventbus中的一个线程池去调用,这里的线程池与BACKGROUND逻辑中的线程池用的是同一个
有参考这位大神的分析并结合自己的理解,给自己做个笔记,感谢大神的分享 EventBus 3.1.1 源码解析

你可能感兴趣的:(EventBus 3.1.1 自己对源码的理解)