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 subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            // 把类和监听的方法关联起来,放在map中,后续有事件时才能找到对应关系触发监听方法
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

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

    List findSubscriberMethods(Class subscriberClass) {
        // 先从Cache里找,如果有对应关系了直接返回,没有则去建立对应关系
        List 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 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> 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).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, 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 eventQueue = new ArrayList(); //事件队列
        boolean isPosting; //是否正在发送
        boolean isMainThread; //是否在主线程发送的
        Subscription subscription; //监听者的信息
        Object event; //事件本身
        boolean canceled; //是否已取消 
    }

public void post(Object event) {
        // 获取PostingThreadState,把事件加到事件队列中
        PostingThreadState postingState = currentPostingThreadState.get();
        List 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> 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实现,那样会得不偿失的。

你可能感兴趣的:(EventBus使用总结)