EventBus源码详解和设计分析(一)观察者订阅与注销

本文EventBus源码基于3.1.1版本

前言

​ EventBus是Android开发最常使用到的通信框架,它的源码和设计相对简单,学习开源框架,从EventBus开始吧。

​ EventBus基于观察者模式,即订阅—— 发布为核心流程的事件分发机制,发布者将事件(event)发送到总线上,然后EventBus根据已注册的订阅者(subscribers)来匹配相应的事件,进而把事件传递给订阅者。流程示意图如下:

image

EventBus的全部代码结构如下:

以上是EventBus的所有代码

注册

EventBus类

EventBus类中最重要的两个变量如下,保存了EventBus中事件和订阅者关系

private final Map, CopyOnWriteArrayList> subscriptionsByEventType;
private final Map>> typesBySubscriber;
  • subscriptionsByEventType:保存事件类型以及所有相关该事件的订阅关系表,即通过事件类型为索引;
  • typesBySubscriber:订阅者与订阅的事件映射列表,即通过订阅者为索引;
Subscription类

​ 保存了订阅者和订阅方法两个变量,并重写了equals和hashCode方法,是一个数据封装类。

final Object subscriber;
final SubscriberMethod subscriberMethod;
volatile boolean active;
  • volatile boolean active:发送事件时判断,防止产生竞态条件。改变量在初始化是置为true,unregister时置为false。
注册register()方法

​ EventBus使用EventBus.getDefault().register(Object o)方法进行注册,并传入一个该观察者subscriber。

getDefault()方法使用双重检验锁创建一个EventBus单例:

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

EventBus.register()方法传入需要注册的观察者,通常是Activity/Fragment。

public void register(Object subscriber) {
        Class subscriberClass = subscriber.getClass();
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //subscribe()方法将subscriber与订阅方法关联起来
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

注册订阅者时,需要完成以下两个流程:

  1. 通过SubscriberMethodFinder.findSubscriberMethods()方法获取包含订阅类所有订阅方法的SubscriberMethod列表;

  2. 遍历subscriber中的所有订阅方法,将subscriber与订阅方法关联起来。

SubscriberMethod类
final Method method;                //订阅方法本身
final ThreadMode threadMode;        //执行线程
final Class eventType;           //事件类型
final int priority;                 //优先级
final boolean sticky;               //是否为粘性事件
/** Used for efficient comparison */
String methodString;                //方法名称,用于内部比较两个订阅方法是否相等

SubscriberMethod类包含以上成员,用来描述订阅方法。

1. findSubscriberMethods方法
List findSubscriberMethods(Class subscriberClass) {
        //METHOD_CACHE是一个Map, List>,保存该类的所有订阅方法
        List subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
            //通过反射去获取被该类中@Subscribe 所修饰的方法
            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;
        }
    }

解析:

  • 如果缓存中有对应class的订阅方法列表,则直接返回------此时是第一次创建,subscriberMethods应为空;

  • 通过ignoreGeneratedIndex参数(默认为false)判断,此时进入else代码块,当查找到所有订阅方法subscriberMethods后,加入到缓存METHOD_CACHE中。

  • 如果查询到订阅方法表为空,则抛出该类/父类没有订阅方法的异常,表明了EventBus3.x不允许一个类注册EventBus却没有需要处理的订阅方法。

1.1 findUsingReflection()方法

​ findUsingReflection方法其核心调用的是findUsingReflectionInSingleClass(),该方法遍历该类中所有方法,找到方法参数为一个 并且包含@Subscribe注解的方法,并检查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 subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    //包含注解@Subscribe的方法
                    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");
            }
        }
    }

如果某个方法包含@Subscribe注解,但是拥有参数数量不为1,或者不是public修饰并且不满足非static 、非abstract,非bridge,非synthetic,会抛出相应异常。

Modifier各静态属性对应表:

PUBLIC: 1 PRIVATE: 2 PROTECTED: 4 STATIC: 8 FINAL: 16 SYNCHRONIZED: 32 VOLATILE: 64 TRANSIENT: 128 NATIVE: 256 INTERFACE: 512 ABSTRACT: 1024 STRICT: 2048

checkAdd()方法如下:

    boolean checkAdd(Method method, Class eventType) {
            // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
            // Usually a subscriber doesn't have methods listening to the same event type.
            Object existing = anyMethodByEventType.put(eventType, method);
            if (existing == null) {
                return true;
            } else {
                if (existing instanceof Method) {
                    if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                        // Paranoia check
                        throw new IllegalStateException();
                    }
                    // Put any non-Method object to "consume" the existing Method
                    anyMethodByEventType.put(eventType, this);
                }
                return checkAddWithMethodSignature(method, eventType);
            }
        }

解析:

  • 在anyMethodByEventType(Map)中检查是否包含eventType的类型,没有返回ture;
  • 如果有该方法,需判断方法的完整签名,checkAddWithMethodSignature如下:
private boolean checkAddWithMethodSignature(Method method, Class eventType) {
    methodKeyBuilder.setLength(0);
    methodKeyBuilder.append(method.getName());
    methodKeyBuilder.append('>').append(eventType.getName());

    String methodKey = methodKeyBuilder.toString();
    //获取该方法所属类的类名
    Class methodClass = method.getDeclaringClass();
    //subscriberClassByMethodKey的put方法返回上一个相同key的类名
    Class methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
    //未添加过该参数的方法;或该类的同类/父类添加过,任一满足返回true
    if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
        // Only add if not already found in a sub class
        return true;
    } else {
        // Revert the put, old class is further down the class hierarchy
        subscriberClassByMethodKey.put(methodKey, methodClassOld);
        return false;
    }
}

A.isAssignableFrom(B)方法判断A与B是否为同一个类/接口或者A是B的父类。

1.2 findUsingInfo()方法

private List findUsingInfo(Class subscriberClass) {
        //获取FindState对象----FindState池中取出当前subscriber的FindState,如果没有则直接new一个新的FindState对象
        FindState findState = prepareFindState();
        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 {
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

getSubscriberInfo()方法如下:初始化时findState.subscriberInfo和subscriberInfoIndexes为空,所以这里直接返回null

private SubscriberInfo getSubscriberInfo(FindState findState) {
        //已经有订阅信息,并且父订阅信息的 Class 就是当前 Class
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }   
        }
        //如果有index,就去index中查找,没有返回 null
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

getMethodsAndRelease()方法:

private List getMethodsAndRelease(FindState findState) {
        //从findState获取subscriberMethods,放进新的ArrayList
        List subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        //回收findState
        findState.recycle();
        //findState存储在FindState池中,方便下一次使用,提高性能
        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;
    }

至此,register方法中拿到了subscriberMethod的list,然后遍历List,通过subscribe方法将每个SubscriberMethod和订阅者关联。

2.subscribe方法
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) {
            //将 事件类型-订阅关系表 保存到subscriptionsByEventType
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            //同一个Subscriber中不能有相同的订阅事件方法
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "+ eventType);
            }
        }

        int size = subscriptions.size();
        //遍历并根据优先级调整顺序,即将Subscription插入到正确位置
        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 {
                //根据eventType,从stickyEvents列表中获取特定的事件
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

分析:

  1. 首先,使用每一个subscriber和subscriberMethod创建一个Subscription;
  2. 根据subscriberMethod.eventType作为Key,在Map---subscriptionsByEventType中获取该事件类型对应的的所有订阅关系列表,并检查是否已存在相同的订阅事件;
  3. 根据优先级添加newSubscription,priority值越大,在List中的位置越靠前,即priority越大,优先级越高;
  4. 向typesBySubscriber中添加subscriber和本subscriber的所有订阅事件。typesBySubscriber是一个保存所有subscriber的Map,key为subscriber,value为该subscriber的所有订阅事件,即所有的eventType列表;
  5. 最后,判断是否是sticky。如果是sticky事件的话,到最后会调用checkPostStickyEventToSubscription()方法分发事件。
图解
image

注销

注销普通订阅事件方法:unregister()
public synchronized void unregister(Object subscriber) {
        List> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

分析:

  1. 获取当前订阅者的所有订阅事件;

  2. 调用unsubscribeByEventType()方法从subscriptionsByEventType中移除当前subscriber的订阅者-订阅事件映射;

  3. typesBySubscriber移除该订阅者;

unsubscribeByEventType()方法
private void unsubscribeByEventType(Object subscriber, Class eventType) {
    //通过事件类型获取所有订阅关系
    List subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        //遍历移除属于当前订阅者的订阅关系
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}
注销粘性事件:removeStickyEvent()
    /**
     * Remove and gets the recent sticky event for the given event type.
     *
     * @see #postSticky(Object)
     */
    public  T removeStickyEvent(Class eventType) {
        synchronized (stickyEvents) {
            return eventType.cast(stickyEvents.remove(eventType));
        }
    }

    /**
     * Removes the sticky event if it equals to the given event.
     *
     * @return true if the events matched and the sticky event was removed.
     */
    public boolean removeStickyEvent(Object event) {
        synchronized (stickyEvents) {
            Class eventType = event.getClass();
            Object existingEvent = stickyEvents.get(eventType);
            if (event.equals(existingEvent)) {
                stickyEvents.remove(eventType);
                return true;
            } else {
                return false;
            }
        }
    }

这两个重载方法最终目的都是从stickyEvents移除订阅事件。

你可能感兴趣的:(EventBus源码详解和设计分析(一)观察者订阅与注销)