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

本文EventBus源码基于3.1.1版本

前言

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

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

image

EventBus的全部代码结构如下:

以上是EventBus的所有代码

注册

EventBus类

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

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> 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<SubscriberMethod> 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<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;
        }
    }

解析:

  • 如果缓存中有对应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<SubscriberMethod> 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<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和订阅者关联。

2.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) {
            //将 事件类型-订阅关系表 保存到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<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,在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<Class<?>> 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<Subscription> 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> T removeStickyEvent(Class<T> 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移除订阅事件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • EventBus基本使用 EventBus基于观察者模式的Android事件分发总线。 从这个图可以看出,Even...
    顾氏名清明阅读 612评论 0 1
  • 项目到了一定阶段会出现一种甜蜜的负担:业务的不断发展与人员的流动性越来越大,代码维护与测试回归流程越来越繁琐。这个...
    fdacc6a1e764阅读 3,147评论 0 6
  • 先吐槽一下博客园的MarkDown编辑器,推出的时候还很高兴博客园支持MarkDown了,试用了下发现支持不完善就...
    Ten_Minutes阅读 555评论 0 2
  • EventBus源码分析(一) EventBus官方介绍为一个为Android系统优化的事件订阅总线,它不仅可以很...
    蕉下孤客阅读 3,966评论 4 42
  • 前言 在上一篇文章:EventBus 3.0初探: 入门使用及其使用 完全解析中,笔者为大家介绍了EventBus...
    丶蓝天白云梦阅读 15,779评论 21 128