Android开发Android技术知识Android开发

EventBus源码和设计分析(一)观察者订阅

2018-07-09  本文已影响5人  Joe_blake

本文EventBus源码基于3.1.1版本

前言

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

​ 它的全部代码结构如下:

以上是EventBus的所有代码

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

image

源码分析

EventBus.getDefault().register(Object o)

​ EventBus使用register()方法进行注册,并传入一个该观察者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<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //subscribe()方法将subscriber与订阅方法关联起来
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

并通过SubscriberMethodFinder.findSubscriberMethods()方法获取订阅类的订阅方法SubscriberMethod列表:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //METHOD_CACHE是一个Map<Class<?>, List<SubscriberMethod>>,保存该类的所有订阅方法
        List<SubscriberMethod> 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;
        }
    }

解析:

  1. 先来看一下findUsingReflection()方法,其核心调用的是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);
                    //包含注解@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");
            }
        }
    }

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

解析:

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赋值,并返回上一个相同key的 类名
    Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
    //未添加过该参数的方法;另外的类添加过但是是该类的同类/父类
    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. findUsingInfo()方法
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        //创建一个新的FindState类----FindState池中取出可用的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) {
        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;
    }

getMethodsAndRelease()方法:

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        //从findState获取subscriberMethods,放进新的ArrayList
        List<SubscriberMethod> 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<SubscriberMethod>,通过subscribe方法将每个SubscriberMethod和订阅者关联。

subscribe方法如下:

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 {
            //同一个Subscriber中不能有相同的订阅事件方法
            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 {
                //根据eventType,从stickyEvents列表中获取特定的事件
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

分析:

  1. 首先,使用每一个subscriber和subscriberMethod创建一个Subscription,类似一个键值对;
  2. 根据subscriberMethod.eventType作为Key,在subscriptionsByEventType的Map中查找一个CopyOnWriteArrayList<Subscription>的list ,如果没有则创建一个新的CopyOnWriteArrayList;然后将这个CopyOnWriteArrayList作为subscriberMethod.eventType的value放入subscriptionsByEventType中;
  3. 根据优先级添加newSubscription,优先级越高,在List中的位置越靠前;
  4. 向typesBySubscriber中添加subscriber和本subscriber的所有订阅事件。typesBySubscriber是一个保存所有subscriber的Map,key为subscriber,value为该subscriber的所有订阅事件,即所有的eventType列表;
  5. 最后,判断是否是sticky。如果是sticky事件的话,到最后会调用checkPostStickyEventToSubscription()方法分发事件。
上一篇下一篇

猜你喜欢

热点阅读