源码分析一:EventBus

260 阅读8分钟

所有入口均在EventBus.java中:

public void post(Object event)

public void register(Object subscriber)

public synchronized void unregister(Object subscriber) 

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

先来看findSubscriberMethods:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //首先从缓存中取出subscriberMethodss,如果有则直接返回该已取得的方法
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //从EventBusBuilder可知,ignoreGenerateIndex一般为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 {
        //将获取的subscriberMeyhods放入缓存中
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

上面代码的作用是查找class是否有标识为观察者的方法,首先从缓存METHOD_CACHE中查找,如果没有再通过反射或者注解的方式来查找。由于ignoreGeneratedIndex默认为false,所以默认是通过注解查找。(当然也可以通过new EventBus(new EventBusBuilder().ignoreGeneratedIndex(true));)来设置用反射来查找观察方法。

所以以下着重看通过注解查找的方法,即findUsingInfo

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    //准备一个FindState,该FindState保存了订阅者类的信息
    FindState findState = prepareFindState();
    //对FindState初始化
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //获得订阅者的信息,一开始会返回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 {
            //1 、到了这里
            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;
    }
    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注解
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    //参数类型 即为 事件类型
                    Class<?> eventType = parameterTypes[0];
                    // 2 、调用checkAdd方法
                    if (findState.checkAdd(method, eventType)) {
                        //从注解中提取threadMode
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        //新建一个SubscriberMethod对象,并添加到findState的subscriberMethods这个集合内
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
                //如果开启了严格验证,同时当前方法又有@Subscribe注解,对不符合要求的方法会抛出异常
            } 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");
        }
    }
}

这里面的逻辑就是通过发射拿到class下所有的所有方法,然后遍历所有方法,当方法入参数量为1,且含有Subscribe.class的注解时候,解析注解内容,保存至findState.subscriberMethods中。

最终会回到return getMethodsAndRelease(findState);

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    //从findState获取subscriberMethods,放进新的ArrayList
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    //把findState回收
    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;
}

至此,SubscriberMethodFinder这个类走完了,回到EventBus#rigister

public void register(Object subscriber) {
    new EventBus(new EventBusBuilder().ignoreGeneratedIndex(true));
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    //继续往下
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

继续看subscribe方法:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    //将subscriber和subscriberMethod封装成 Subscription
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //根据事件类型获取特定的 Subscription,subscriptionsByEventType 是以event事件作为key,CopyOnWriteArrayList<Subscription>作为value的map,
    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);
        }
    }
    //根据优先级来设置放进subscriptions的位置,优先级高的会先被通知
    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;
        }
    }
    //根据subscriber(订阅者)来获取它的所有订阅事件,以订阅的类为value,类订阅方法list作为value的map
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        //把订阅者、事件放进typesBySubscriber这个Map中
        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);
        }
    }
}

可以看到最终会保存到2个map中去。

一个map是Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

另外一个是Map<Object, List<Class<?>>> typesBySubscriber;

subscriptionsByEventType是以event事件作为key,CopyOnWriteArrayList<Subscription>作为value的map,其中CopyOnWriteArrayList<Subscription>作用是保存各个优先级不同Subscription。

typesBySubscriber是以订阅者及注册类作为key,类订阅方法list作为value的map。

至此,所有调用即已结束。

下面盗一张别人的图来展示整个过程:


分析unRegister

public synchronized void unregister(Object subscriber) {
    //根据当前的订阅者来获取它所订阅的所有事件
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        //遍历所有订阅的事件
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        //从typesBySubscriber中移除该订阅者
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

上面调用了EventBus#unsubscribeByEventType,把订阅者以及事件作为参数传递了进去,那么应该是解除两者的联系。

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //根据事件类型从subscriptionsByEventType中获取相应的 subscriptions 集合
    List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        //遍历所有的subscriptions,逐一移除
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}

可以看到,上面两个方法的逻辑是非常清楚的,都是从typesBySubscriber或subscriptionsByEventType移除相应与订阅者有关的信息,注销流程相对于注册流程简单了很多,其实注册流程主要逻辑集中于怎样找到订阅方法上。

分析post:

发送事件调用:

EventBus.getDefault().post(new MessageEvent("Hello !....."));

/** Posts the given event to the event bus. */
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;
        }
    }
}

其中currentPostingThreadState是 

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

为什么需要用ThreadLoacl来保存,目前还不清楚。(线程安全?)

ThreadLoacl保存的PostingThreadState是如下结构

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

过程是先从线程中拿到PostingThreadState对象,并往PostingThreadState.eventQueued队列中添加当前event事件。做一些是否状态设置,然后最终调用postSingleEvent。

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //该eventInheritance上面有提到,默认为true,即EventBus会考虑事件的继承树
    //如果事件继承自父类,那么父类也会作为事件被发送
    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 (logNoSubscriberMessages) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

可以看到会查找event的所有父类,一起发送给订阅者。接着调用了

EventBus#postSingleEventForEventType

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //从subscriptionsByEventType获取响应的subscriptions
        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;
            } 
            //...
        }
        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 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,即订阅方法运行的线程,如果是POSTING,那么直接调用invokeSubscriber()方法即可,如果是MAIN,则要判断当前线程是否是MAIN线程,如果是也是直接调用invokeSubscriber()方法,否则会交给mainThreadPoster来处理,其他情况相类似。而EventBus#invokeSubscriber的实现也很简单,主要实现了利用反射的方式来调用订阅方法,这样就实现了事件发送给订阅者,订阅者调用订阅方法这一过程。如下所示:

invokeSubscriber

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

到目前为止,事件的发送流程也讲解完毕,为了方便理解,整个发送流程也给出相应的流程图:


结语

至此,EventBus的主要源码分析完毕。完成了订阅、反订阅、发送及响应消息的过程的源码细解析。

EventBus实质上是观察者模式的实现,观察者是订阅类,被观察者是Event事件,随着Event事件发出或者改变时候,会通过EventBus通知订阅类,然后通过发射调用订阅类的方法。

核心数据是2个map,一个用来保存所有Event事件所对应的注解和操作数据,一个用来保存所有订阅者所对应的方法数据。

核心流程就是贴出的2张图。

核心方法包括反射和注解:

反射有2处:1、用于查找订阅类的所有需要通知的方法,2、用于调用订阅类的订阅方法。

注解:注解用于解析订阅类的方法所包含的订阅信息(包括订阅的线程、所订阅的优先级)。