EventBus使用总结

概述

EventBus是Android开发最常用的一个库了,它给我们带来了很好便利性,轻松实现消息的发布和订阅。但凡事都有两面性,合理的使用就是好事,不合理的使用可能就会有各种问题了,下面我们来看看它的源码实现。

源码分析

EventBus使用简单,注册反注册发送监听都非常简单,易上手。来看一下它的使用吧。

注册:EventBus.getDefault().register(this);
发布:EventBus.getDefault().post(event);
反注册:EventBus.getDefault().unRegister(this);

先看看EventBus的getDefault方法

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

就是获取EventBus实例,这里用的是全局单例,方便使用。

再看看register方法的实现

    public void register(Object subscriber) {
        // 获取观察者的类型
        Class<?> subscriberClass = subscriber.getClass();
        // 通过subscriberMethodFinder找到这个观察者里所有的监听方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            // 把类和监听的方法关联起来,放在map中,后续有事件时才能找到对应关系触发监听方法
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

一起看一下subscriberMethodFinder是怎么打到观察者里的监听方法的

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 先从Cache里找,如果有对应关系了直接返回,没有则去建立对应关系
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        // 这里有个判断,是否忽略编译时用工具生成的index文件
        // EventBus有一个工具可以在编译期间就把观察者和注解的监听方法关联起来,生成一个java文件,避免运行时通过反射进行查找,加快了运行速度,提高性能
        if (ignoreGeneratedIndex) {
            // 通过反射的方式去找到所有注解的监听方法
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            // 通过编译生成的java文件进行查找
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            // 找到后put到cache里
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

代码通过注释说清楚了监听方法的过程,通过反射就是找使用了@Subscribe注解的函数,并读取其中的配置,比如threadMode等,更于后面发送事件时使用。这里就不贴反射的具体代码了。

要说的就是SubscriberMethod类了,看看这里有哪些成员变量:

public class SubscriberMethod {
    final Method method; //方法,用于反射回调的
    final ThreadMode threadMode; //指定的线程
    final Class<?> eventType; //事件的类型,后续要通过这个找相关的监听方法
    final int priority; //优先级
    final boolean sticky; //是否接收粘性事件
}

找到所有监听的方法后,会通过subscribe方法进行关联,来看具体实现:

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        // Subscription是监听方法subscriberMethod和观察者subscriber绑定关系,用于后面反射调用方法的
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // subscriptions是此监听方法中的事件类型对应的所有subscriptions,是以事件类型为key的
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        // 如果不存在则新建一个,再把新找到的SubscriberMethod添加进去,这样后面发送此事件类型时它才能被触发
        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;
            }
        }

        // 这里是从另一个角度看了,获取观察者所有监听的事件类型,之前是根据事件类型找不同观察者的方法,这里是根据观察者类找它所有监听的事件类型,这是为了反注册时用的
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        // 如果方法是支持粘性事件的,就会从粘性事件缓存里找到最近一次的事件,直接通过checkPostStickyEventToSubscription进行事件发送
        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);
            }
        }
    }

总结下注册的逻辑:

  1. 找到观察者里所有的监听方法
  2. 循环把所有监听方法和事件类型的关系保存下来
  3. 如果支持粘性事件就找最近一次同类型事件进行发送

再来看下发送的源码实现;

先看下相关的类说明:

 /** For ThreadLocal, much faster to set (and get multiple values). */
    final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>(); //事件队列
        boolean isPosting; //是否正在发送
        boolean isMainThread; //是否在主线程发送的
        Subscription subscription; //监听者的信息
        Object event; //事件本身
        boolean canceled; //是否已取消 
    }
public void post(Object event) {
        // 获取PostingThreadState,把事件加到事件队列中
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        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()) {
                    // 这里是发送事件的方法
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

postSingleEvent->postSingleEventForEventType->postToSubscription这里发送事件方法的调用路径,postSingleEventForEventType其实就是通过事件类型从我们注册时存储的对应关系里找到此事件对应的所有监听信息Subscriptions,然后逐个调用。我们直接看postToSubscription的实现:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            // 这里都是通过invokeSubscriber反射的形式调用监听方法的
            // 默认值,哪个线程抛出的事件就在哪个线程处理
            case POSTING:
                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;
            // 总是空闲线程去调用,它和BACKGROUND的区别就是总是开一个新线程去处理,BACKGROUND如果发送线程本来就是非主线程,就直接在当前线程处理了
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

postSticky的实现只是在调用前把事件先存到stickyEvents,用于注册支持sticky的监听方法时使用,后面还是调用了post方法。

 public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

总结下发送的逻辑:

  1. 如果是粘性事件就把事件存起来
  2. 通过事件类型找到所有相关的监听方法
  3. 通过反射在指定的处理线程中调用监听方法

最后看下反注册的源码实现:

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

总结下反注册的逻辑:
就是把注册时存储的对应关系一一解除。

总结

EventBus的优点:

  1. 易用性:使用简单易上手
  2. 轻耦合:使用它就是为了替换回调函数,避免模块间的强耦合
  3. 线程切换:EventBus通过注解里的threadMode可以轻松指定处理的线程

EventBus的缺点:

代码变得不易读,不好发现哪里调用了事件发送及哪里做了事件;

如果项目里滥用了,会出现要区分来源的问题。

举个例子,请求获取一个实时性比较强的数据,不同时间请求的结果会不一样,请求结果回来后用EventBus抛出结果,需要的进行监听。A界面执行了请求,请求没结束前就跳转到B界面,B界面同样调用了这个请求,这里结果回来的速度不一样,B界面就会收到两个EventBus的事件,导致处理错误。

解决办法有两个:

  1. A界面跳转到B界面后,取消A界面的请求,避免重复数据发送(正常都要做的事情)
  2. 对所有的事件增加来源标识(可以用这个界面类的hashcode),B界面收到后可以判断来源是否是自己发的请求,如果不是,则不处理。但这就要求发请求时要把这个标识带上了。

EventBus基本上是开发应用必备的第三方库了,总得来说好处多多,但还是要适当使用,别看它那么好用就一冲动就把所有Callback换成EventBus实现,那样会得不偿失的。

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

推荐阅读更多精彩内容

  • 1.EventBus是一个基于观察者模式的事件发布/订阅框架,开发者通过极少的代码去实现多个模块之间的通信,而不需...
    newszhu阅读 412评论 0 0
  • 为什么要用EventBus:EventBus是一个事件总线框架,观察者模式的变形,利用这个框架,我们可以方便高效地...
    文文太远了阅读 662评论 0 1
  • EventBus是Android中的发布/订阅事件总线。github链接 目前应该还算是最流行的,另外还有Otto...
    kolen_j阅读 248评论 0 2
  • 项目到了一定阶段会出现一种甜蜜的负担:业务的不断发展与人员的流动性越来越大,代码维护与测试回归流程越来越繁琐。这个...
    fdacc6a1e764阅读 3,147评论 0 6
  • 笔记概述 EventBus简介 EventBus方法介绍 EventBus实际运用 EventBus简介 开源项目...
    凌川江雪阅读 602评论 0 2