EventBus源码解析

Android框架学习

Posted by Cc1over on January 5, 2020

EventBus源码解析

注册

EventBus-> register

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

方法流程:

  • 先根据传入的subscriber拿到它的class对象
  • 然后调用findSubscriberMethods拿到subscriber中有subscriber注解的method
  • 然后遍历收集的方法集调subscribe方法

SubscriberMethodFinder-> findSubscriberMethods

private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

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

方法流程:

  • 首先从METHOD_CACHE缓存中拿到对应class的subscriberMethod集合,然后存在就直接返回
  • 然后根据ignoreGeneratedIndex参数判断转调哪个方法根据subcriberClass拿到subscriber方法集合,它的默认值为false

SubscriberMethodFinder-> findUsingInfo

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

方法流程:

  • 调用prepareFindState方法从对象池中拿到一个FindState对象并初始化
  • 调用getSubscriberInfo拿到SubcriberInfo,而SubscriberInfo其实就是Class和Subsriber方法信息之间关系的封装
  • 然后做一下校验工作之后就把拿到的方法集合添加到findState中
  • 接下来就是再往上找父类

SubscriberMethodFinder-> getSubscriberInfo

private SubscriberInfo getSubscriberInfo(FindState findState) {
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

方法流程:

  • 遍历从EventBusBuilder中传进来的subscriberInfoIndexes,然后通过index根绝subscriberClass拿到SubscriberInfo

SubscriberInfoIndex-> getSubscriberInfo

public interface SubscriberInfoIndex {
    SubscriberInfo getSubscriberInfo(Class<?> subscriberClass);
}
  • SubscriberInfoIndex是一个接口,因为实现类是通过apt生成的
/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEventA", PayEvent.class, ThreadMode.ASYNC),
        }));

        putIndex(new SimpleSubscriberInfo(MyIntentService.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEventBB", PayEvent.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }

设计思路:

  • 通过apt实现在编译器生成SubscriberInfoIndex的实现类,然后这个实现类维护了一个Map<Class,SubscriberInfo>,然后在static块就把SubscriberClass和SubscriberInfo存进这个Map中
  • 而SubscriberInfo其实就是Class和Subsriber方法信息之间关系抽象的数据结构
  • 所以用这种apt的方式做Class和SubscriberInfo的映射就不需要反射找方法了,这也是这个类命名叫index的原因吧

SimpleSubscriberInfo-> getSubscriberMethods

@Override
    public synchronized SubscriberMethod[] getSubscriberMethods() {
        int length = methodInfos.length;
        SubscriberMethod[] methods = new SubscriberMethod[length];
        for (int i = 0; i < length; i++) {
            SubscriberMethodInfo info = methodInfos[i];
            methods[i] = createSubscriberMethod(info.methodName, info.eventType, info.threadMode,
                    info.priority, info.sticky);
        }
        return methods;
    }
  • 其实就是把SubscriberInfo储存方法信息转存并返回

SubscriberMethodFinder-> getMethodsAndRelease

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> 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;
    }
  • 把FindState中的methods信息取出来,然后回收到对象池中

小结

到这里其实针对apt的Subscriber方法查找的流程就走完了,其实原理就是

  • 通过apt生成SubscriberInfoIndex的子类,然后在这个类中维护了一个Map储存了Class和Subscriber方法的映射的关系
  • 然后在注册阶段就可以以Class为索引找到对应SubscriberInfo对象,SubsriberInfo对象储存了对应类中所有的Subsriber方法以及Event类型的信息
  • 通过这种优化策略就可以避免在注册过程中使用反射找到这些Subsriber方法

SubscriberMethodFinder-> findUsingReflection

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }
  • 这个方法的执行流程和findUsingInfo方法很类似,就是少了那部分根据index查找info再找方法的逻辑
  • 而是直接采用反射进行Subsriber方法的搜索

SubscriberMethodFinder-> findUsingReflectionInSingleClass

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;
        }
        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,是否有需要忽略修饰符,如果既不是public,又不需要忽略修饰符就抛出异常
  • 如果是public的修饰符:
    • 方法参数只有一个:这就说明EventBus只允许Subscriber方法绑定的Event只能是一个,然后再判断是不是被Subscribe注解修饰,如果是,就从注解中拿到线程信息,然后进行一些校验工作之后就把方法添加到FindState中
    • 如果是strict校验模式而且Event不止一个,就抛出异常
    • 如果是strict校验模式而且Subscribe方法不是public,非静态,非抽象就抛出异常

EventBus-> subscribe

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        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);
            }
        }
    }

方法流程:

  • 从subscriberMethod中拿到绑定的Event的类型,然后创建一个Subscription对象,其实就是对subscriberMethod和subscriber的一层封装
  • 然后在EventBus中维护一个subscriptionsByEventType,也就是Map<Event类型,Subscription集合>,然后就是根绝Event类型拿到这个Subscription集合,根据优先级把Subscription插入到这个集合中
  • 然后在EventBus还维护一个typesBySubscriber,也就是Map<接收者Object,subscribed的所有Event类型列表>,然后把这个Event的类型添加到对应的subscriber的类型列表中
  • 然后就是对sticky的处理,这里很有意思,通过eventInheritance这个标记位做区分处理:
    • eventInheritance为true:会判断当前Event有没有父类,没有就直接做一次方法调用,如果有父类就往上找它的父类
    • eventInheritance为false:直接做一次方法调用

小结

总的来说注册的过程分为2步:

搜索方法:

  • apt在编译器生成一个SubscriberIndex类,维护一个Map储存Class和SubscriberInfo的关系,SubscriberInfo则保存所有Subscribe方法名称以及Event的类型,用这种方式避免了在注册过程中反射搜索方法
  • 通过反射拿到Class的所有方法,然后遍历参数只有1个的方法找它是否被注解修饰

注册:

  • 注册这一步操作说明白了就是把信息缓存在EventBus中
  • 注册部分中涉及的EventBus缓存包含两个:
    • Map<Event类型,Subscription集合> subscriptionsByEventType,用于记录Event类型和接收地的关系,Subscription不止包含Subsriber,还包含了接收方法
    • Map<接收者Object,subscribed的所有Event类型列表>,用于记录接收者所关注的所有事件类型

发送Event

EventBus-> post

private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

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

方法流程:

  • 拿到当前线程的PostingThreadState对象,这个对象其实就是线程信息的封装,在PostingThreadState中还维护了一个event队列,然后post会把event添加到这个队列中
  • isPosting这个标记其实就是用来控制并发,在post过程中,当前线程的其他post操作无法生效
  • 然后给postingState赋值是否为主线程,isPosting置为true
  • 转调postSingleEvent函数,遍历eventQueue进行Event发送

PostingThreadState

final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<>();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }

EventBus-> postSingleEvent

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 (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

方法流程:

  • 这里依然有对eventInheritance标记位的兼容,与注册时同理是为了对继承关系进行处理
  • 而实际的subscription搜索和Event发送都是由postSingleEventForEventType方法执行的

EventBus-> postSingleEventForEventType

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

方法流程:

  • subscriptions集合的获取就是根据注册时候填入的Map,根据Event的class拿到所有subscriptions的集合
  • 然后给postingState,也就是当前线程发送状态赋值信息
  • 转调postToSubscription方法发送消息

EventBus-> 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);
        }
    }
  • 根据方法搜索时储存的threadMode这个字段,根据不同情况进行处理
  • 主要的思想就是判断当前是否处于指定的线程,是的话就直接invokeSubscriber,不是的话就加入队列中
  • 但是MAIN_ORDERED这种情况下,不管是否处于指定线程都会入队,这样就保证了顺序
  • 而ASYNC就是相反了,不管是否处于指定线程都直接入队,从而异步
  • 而非主线程的Poster本身也是一个Runnable,会不停从队列中取出事件去发送,而本质其实也是调用invokeSubscriber方法,而EventBus会维护一个线程池执行这些线程
  • 而主线程的Poster的线程切换的秘密其实也还是通过Handler去实现的

EventBus->invokeSubscriber

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);
        }
    }
  • 可见实际在找到对应关系之后就是通过invoke调用subscribe方法即可

EventBus-> postSticky

public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }
  • 把sticky的event用一个Map保存起来,key依旧是event的类型
  • 转调post方法,而当接收方还没有被register的情况下postSingleEventForEventType就会因为subscriptions为null而退出了

总结

EventBus这个框架的设计思想其实就是通过apt或者反射找到了被注解描述的方法缓存起来,然后当调post的时候从早就做好的这个缓存中找到目标,反射调用一下就好了

而对粘性事件,其实也是活用了缓存,postSticky的时候缓存起来,注册的时候检查缓存中是否存在粘性事件,存在就调用目标方法就好了