EventBus 源码分析

疑问:
EventBus 注册,发送事件,注销时分别做了哪些操作?
1、EventBus.getDefault().register(Object)、
2、EventBus.getDefault().post(Object)
3、EventBus.getDefault().unregister(Object)

1、EventBus.getDefault().register(Object)
步骤一

首先通过 EventBus.getDefault() 获取 EventBus 单例

    //EventBus 单例对象
    static volatile EventBus defaultInstance;
    //默认 EventBusBuilder
    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    //获取单例 EventBus
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

    public EventBus() {
        this(DEFAULT_BUILDER);
    }
    //初始默认值
    EventBus(EventBusBuilder builder) {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

下面再看 register() 方法

    public void register(Object subscriber) {
        //1、获取注册对象的 class 对象 subscriberClass
        Class<?> subscriberClass = subscriber.getClass();
        //2、通过 class 对象 subscriberClass 找到该 class 的 SubscriberMethod 集合
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //3、订阅注册对象支持注解 @Subscribe 的方法
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

其中 SubscriberMethod 用来保存订阅方法的信息

public class SubscriberMethod {
    //方法
    final Method method;
    //线程类型(ThreadMode.POST、ThreadMode.MAIN...)
    final ThreadMode threadMode;
    //事件类型,即发送的事件
    final Class<?> eventType;
    //优化级
    final int priority;
    //是否粘性事件
    final boolean sticky;
}

第二步找到注册对象中 @Subscribe 注解的方法列表,并将每个方法保存在 SubscriberMethod 中。第三步订阅注解的方法列表。下面先看第二步

步骤二
class SubscriberMethodFinder {

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //METHOD_CACHE 是一个 Map,用来缓存注册对象 Class 内所有的被@Subscribe注解的方法集合
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        //优先从缓存中取
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //ignoreGeneratedIndex 默认值为 false,
        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            //2.1、查找注册对象订阅方法列表
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            //查找到的订阅方法加入到缓存中,key 为注册对象的 class 
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        //初使化 FindState 对象
        FindState findState = prepareFindState();
        //给 findState.subscriberClass 赋值,关联注册对象
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //subscriberInfo 默认为空,高级用法暂不分析
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                    ...
                }
            } else {
                //2.2 使用反射查找注册对象的订阅方法集合,存放在 findState 中
                findUsingReflectionInSingleClass(findState);
            }
            //移到父类,继续 while 循环
            findState.moveToSuperclass();
        }
        //从 findState 中获取订阅方法集合,并释放 findState 对象
        return getMethodsAndRelease(findState);
    }

    //享元模式,降低创建 FindState 对象的数量,减小内存开销
    private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
    private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }
    //重置 FindState 状态,并返回注册对象订阅的方法集合
    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;
    }
}

先具体看下 moveToSuperclass(),将 clazz 赋值给父类,所以也会去父类中查找订单事件,上面的 while 循环 clazz == null

        void moveToSuperclass() {
            if (skipSuperClasses) {
                clazz = null;
            } else {
                clazz = clazz.getSuperclass();
                String clazzName = clazz.getName();
                /** Skip system classes, this just degrades performance. */
                if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
                    clazz = null;
                }
            }
        }

再去看 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) {
            //获取方法的修饰符(public、private)
            int modifiers = method.getModifiers();
            //方法的修饰符必须是 public
            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];
                        if (findState.checkAdd(method, eventType)) {
                            //获取线程模型
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            //方法名、参数、线程类型、粘性 信息存放在 SubscriberMethod 中,放加入到 subscriberMethods 集合中
                            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");
            }
        }
    }

以上完成步骤 2 中对象注册对象的订阅方法集合,下面梳理一下:
1、获取单例 EventBus 对象,并获取注册对象的 class 对象 subscriberClass
2、获取注册对象的订阅方法集合 subscriberMethods,优先从缓存 METHOD_CACHE 中以 class 为 key 获取其 value ,获取不到再通过反射获取。
3、获取不到时,初例化 FindState 对象,将 subscriberClass 赋值给 FindState.clazz
4、反射获取 subscriberClass 的所有方法,遍历所有方法,将 public 修饰、只有一个参数且添加 Subscribe 注解的方法名,包装成 SubscriberMethod 对象并添加到 subscriberMethods 中。
5、将 subscriberClass 的父类赋值给 FindState.clazz,获取父类的订阅方法,重复第 4 步,直到没有父类。
6、重置 FindState 对象状态,返回注册对象的订阅方法集合 subscriberMethods

步骤三

正式注册订阅


    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //获取 event 类型
        Class<?> eventType = subscriberMethod.eventType;
        //将注册对象 subscriber 和 订阅方法 subscriberMethod 包装在 Subscription 中
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //获取 event 的订阅集合 subscriptions,可以理解成用来存放所有注册对象订阅过该 event 的方法
        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;
            }
        }
        //将 subscribedEvents 以 subscriber 为 key 添加到 typesBySubscriber 中即注册对象,unreigster 时会进行 remove
        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();
                    //如果 candidateEventType 是 eventType 的子类或者接口,发送粘性事件
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

以上则是注册对象的流程,下面看发送事件 post()

2、EventBus.getDefault().post(Object)
    public void post(Object event) {
        //获取 PostingThreadState,currentPostingThreadState 是 ThreadLocal,可以当前线程的 PostingThreadState 对象
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //把 event 添加到事件集合中
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    //1、当事件不为空时,发送消息
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
     //提供 PostingThreadState
    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        //eventInheritance 默认为 true
        if (eventInheritance) {
            //查找 event 的所有 Class 对象,包括超类和接口,优先从缓存读取
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                //2、发送事件
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else 
        ...
    }

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            //获取订阅过 event 的所有注册对象的所有订阅方法
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                    ...
                    //3、真正发送 event 事件
                    postToSubscription(subscription, event, postingState.isMainThread);
                    ...
            }
            return true;
        }
        return false;
    }
    //发送事件
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            //订阅的线程模式为当前线程
            case POSTING:
                //4、执行订阅方法
                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);
        }
    }

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

第四步在主线程、后台线程执行用的是 Handler 、Thread 等实现原理较简单,最终调用订阅方式一样都是 invokeSubscriber,故不做分析。

下面把 post() 流程梳理一下:
1、获取当前线程对象,把 event 添加到 eventQueue 中,遍历 eventQueue 不为空时,发送消息。
2、查找 event 的所有 Class 对象,包括超类和接口,优先从缓存读取,lookupAllEventTypes()。
3、取订阅过 event 的所有注册对象的所有订阅方法,遍历一个个去发送事件。
4、处理订阅线程模式,使用反射执行订阅方法。

3、EventBus.getDefault().unregister(Object)

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 {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

知识点小结:
1、EventBus 使用了享元模式,降低了内存中对象的数据。
2、使用了线程安全的 CopyOnWriteArrayList 确保数据安全。
3、使用 ThreadLocal 确保对象线程间共享。
4、使用反射执行订阅方法


参考:
EventBus源码详解,看这一篇就够了

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

推荐阅读更多精彩内容

  • 简介 前面我学习了如何使用EventBus,还有了解了EventBus的特性,那么接下来我们一起来学习EventB...
    eirunye阅读 452评论 0 0
  • EventBus源码分析 Android开发中我们最常用到的可以说就是EventBus了,今天我们来深入研究一下E...
    BlackFlag阅读 489评论 3 4
  • 前面对EventBus 的简单实用写了一篇,相信大家都会使用,如果使用的还不熟,或者不够6,可以花2分钟瞄一眼:h...
    gogoingmonkey阅读 309评论 0 0
  • EventBus 源码分析 分析源码之前 EventBus 大神的 github,最好的老师。 一、使用 我们在平...
    猪_队友阅读 349评论 0 4
  • http://www.jianshu.com/p/518d424d4994 我们先看个例子:$("a").css(...
    01562c97bf42阅读 159评论 0 1