What?EventBus的核心竟然只是这两个Map?

简单介绍一下EventBus

其实EventBus大家都很熟悉了,就不过多去说它了。通常我们叫它事件总线,其实它更像是广播,观察者模式,一方发送消息多方接收。在EventBus的创建订阅过程中,最重要的就是有两个关键的Map,这两个键值对里面存储了我们定义的订阅方法和相关的类,那到底是具体是怎么操作的呢,来源码一探究竟。

下面的代码基于EventBus3.1.1

创建和订阅消息

注册

EventBus的注册很简单,

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

这里一定要记住在onStop中注销,避免在Activity关闭后还跟EventBus有联系,然后造成内存泄漏。

接下来进入到方法中看一看:

单例模式

EventBus.getDefault

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

这个方法很简单,就是双重校验单例,继续看register方法:

register方法

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

在register中,传入的参数名为subscriber,意思就是订阅者,类型为Object。在这个方法里有个List<SubscriberMethod>的列表,这个SubscriberMethod是什么呢?

public class SubscriberMethod {
    final Method method;//对应的方法
    final ThreadMode threadMode;//线程模式
    final Class<?> eventType;//消息类型
    final int priority;//优先级
    final boolean sticky;//是否支持粘性
    /** Used for efficient comparison */
    String methodString;//用于equal对比
}

其实这个类就保存了我们订阅者里面定义的方法里面的所有信息。

线程模式

其中threadMode的定义如下:

  • ThreadMode.POSTING:默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高。

  • ThreadMode.MAIN:如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。

  • ThreadMode.MAIN_ORDERED:无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。

  • ThreadMode.BACKGROUND:如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件。

  • ThreadMode.ASYNC:无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。

所以在register方法中的这个列表其实就是当前我们这个订阅者类包含所有的接收方法。这里通过subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法获取:

查找订阅事件的方法(接收消息的方法)

SubscriberMethodFinder findSubscriberMethods


    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);//首先从缓存中获取
        if (subscriberMethods != null) {
            return subscriberMethods;//缓存有的话直接返回
        }

        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 {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);//加入到缓存中
            return subscriberMethods;
        }
    }

这里我们注意到有一个ignoreGeneratedIndex参数,这个属性的值是在构造方法中获取的

subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    /** Forces the use of reflection even if there's a generated index (default: false). */
    public EventBusBuilder ignoreGeneratedIndex(boolean ignoreGeneratedIndex) {
        this.ignoreGeneratedIndex = ignoreGeneratedIndex;
        return this;
    }

从官方的注释可以看出,这里默认值是false,所以是调用findUsingInfo方法:


    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);//初始化查找辅助类
        while (findState.clazz != null) {//这里就是我们register的类
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {//初始状态为空,所以执行else
                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);//释放资源
    }

FindState是查找辅助类,里面存储了关于查找到的订阅方法信息和相关类的信息:

static class FindState {
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();//订阅的方法
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();//通过消息类型获取方法
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();//通过方法获取订阅的类
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class<?> subscriberClass;
        Class<?> clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;
}

在这里会执行else里面的findUsingReflectionInSingleClass方法,通过反射来查找订阅方法

SubscriberMethodFinder 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) {//public,非abstract、static
                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注解的方法,然后将方法的信息加到数组当中。在查找完毕之后,接下来回到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);
            }
        }
    }

循环订阅

拿到我们刚才的所有订阅方法的数组,然后在循环中执行subscribe方法,这个方法执行订阅操作:

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;//获取我们自定义的消息类型
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//新建一个订阅类,这个类包含了订阅的类和方法两个属性
        //subscriptionsByEventType是以eventType为key,Subscription数组为value的map
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {//为空的话创建数组,并加入到map中
            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;
            }
        }
        //typesBySubscriber是以对象为key,订阅的方法的数组为value的map
        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 {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

其实EventBus的register方法的内部具体做的事情很简单,总的来说就是两步:

  1. 通过反射查找我们使用了Subscribe注解的订阅方法
  2. 循环遍历找到的方法,然后加到关键的两个map中(subscriptionsByEventTypetypesBySubscriber

subscriptionsByEventType:以eventType为key,Subscription数组为value

typesBySubscriber:以对象为key,订阅的方法的数组为value

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

推荐阅读更多精彩内容

  • 先吐槽一下博客园的MarkDown编辑器,推出的时候还很高兴博客园支持MarkDown了,试用了下发现支持不完善就...
    Ten_Minutes阅读 573评论 0 2
  • EventBus是一个Android开源库,其使用发布/订阅模式,以提供代码间的松耦合。EventBus使用中央通...
    壮少Bryant阅读 666评论 0 4
  • 我每周会写一篇源代码分析的文章,以后也可能会有其他主题.如果你喜欢我写的文章的话,欢迎关注我的新浪微博@达达达达s...
    SkyKai阅读 24,987评论 23 184
  • EventBus 是一款在 Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发...
    SheHuan阅读 65,738评论 13 186
  • 项目地址:EventBus,本文分析版本: 3.1.1 一、概述 EventBus 是一个 Android 事件发...
    Yi__Lin阅读 1,052评论 1 10