EventBus源码学习笔记

前言

最近阅读了EventBus(3.0.0)的源码,这里也是记录下自己对EventBus的理解,功力善浅,如有错误地方还望各位大佬及时指正。

1、EventBus的简单使用

1、注册与反注册
@Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

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

关联Activity或者Fragment的生命周期,在onStart方法中注册,在onStop方法中反注册,防止内存泄漏

2、定义事件实体类
public class MessageEvent {
    public String message;

    public MessageEvent(String message) {
        this.message = message;
    }
}

一个简单的事件实体类,将发送消息的内容存储于这个类的实例中

3、定义接收消息的方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Log.d(TAG,"收到了一条EventBus消息" + event.message);
    }

这里有一个Subscribe注解,括号里的threadMode = ThreadMode.MAIN指定了方法执行的线程,3.0以后方法名onMessageEvent支持修改。收到了MessageEvent 的消息便会在主线程执行此方法。同时threadMode目前有四种线程模式:

  • ThreadMode.POSTING:方法在post方法执行的线程中执行
  • ThreadMode.MAIN:方法在主线程中执行
  • ThreadMode.BACKGROUND:方法在后台线程中执行
  • ThreadMode.ASYNC:方法在非post方法执行的后台线程中执行
4、发送消息
    EventBus.getDefault().post(new MessageEvent("我是一条EventBus消息"));

发送消息后我们接收的消息方法便会执行。

2、EventBus实现流程

1、 EventBus的getDefault()

我们可以发现无论是我们注册和反注册还是发送消息,我们都是先调用了EventBus的getDefault方法。这里我们先看一下这个方法

  static volatile EventBus defaultInstance;
   /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

很明显这里是获得一个EventBus类的单例。我们再来看一下EventBus的构造方法

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
 /**
     * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
     * central bus, consider {@link #getDefault()}.
     */
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
         //存放订阅事件对应的Subscription(封装订阅者对象对应的订阅事件封装容器类SubscriberMethod的容器类)对象集合
        subscriptionsByEventType = new HashMap<>();
        //存放订阅者对象对应订阅事件的集合
        typesBySubscriber = new HashMap<>();
        //粘性事件订阅事件对应的订阅者对象集合
        stickyEvents = new ConcurrentHashMap<>();
        //主线程的handler对象,主要是用来执行在订阅在主线程执行的事件
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        //后台线程的Runnable,主要是通过线程池成员变量executorService来执行订阅在后台线程执行的事件
        backgroundPoster = new BackgroundPoster(this);
        //异步线程的Runnable,主要是通过线程池成员变量executorService来执行订阅在非当前线程执行的事件
        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;
    }

可以看出无参构造函数调用了有参构造函数,参数是一个EventBusBuilder 实例。有参构造里面也是对EventBus的成员变量进行赋值,部分也是直接赋值于EventBusBuilder 的成员变量,其实看到Builder我们就很容易猜到这里也是采用了构建者模式,除了通过getDefault方法获得EventBus实例,我们也可以通过EventBusBuilder来设置成员变量来构建EventBus实例。这里就不细说了。

2、EventBus的register

接下来我们再来看一下注册的实现。

/**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * 

* Subscribers have event handling methods that must be annotated by {@link Subscribe}. * The {@link Subscribe} annotation also allows configuration like {@link * ThreadMode} and priority. */ public void register(Object subscriber) { Class subscriberClass = subscriber.getClass(); //通过subscriberMethodFinder找到订阅对象中的所有订阅事件方法 List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { //遍历订阅对象中所有的订阅事件,将其缓存到EventBus的subscriptionsByEventType集合中 for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }

这里先是拿到了注册对象的class对象,然后调用了SubscriberMethodFinder类的findSubscriberMethods方法

private static final Map, List> METHOD_CACHE = new ConcurrentHashMap<>();
List findSubscriberMethods(Class subscriberClass) {
        //先从METHOD_CACHE集合中查找订阅者对应的订阅事件集合
        List subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //是否忽略注解器生成的MyEventBusIndex类,默认为false
        if (ignoreGeneratedIndex) {
            //通过反射查找订阅者类中对应的订阅事件集合
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            //通过注解器生成的MyEventBusIndex类查找订阅者类中对应的订阅事件集合
            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集合中
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

METHOD_CACHE 是一个ConcurrentHashMap,我们之前在Retorfit中看到过这个,这是一个线程安全的map集合。SubscriberMethodFinder类的ignoreGeneratedIndex是一个布尔类型的,EventBus在创建SubscriberMethodFinder实例时给这个变量赋值是直接采用了EventBusBuilder的ignoreGeneratedIndex的值,默认情况下是false。接着会继续findUsingInfo方法,

 private List findUsingInfo(Class subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //通过MyEventBusIndex类获取订阅者类中对应的订阅事件集合
            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);
    }

这里FindState实例相当于一个临时的存储器,findUsingReflectionInSingleClass方法来检查注册类里面是否带有 @Subscribe注解的方法,并检测其合法性(是否是共public方法,是否非静态,是否只有一个参数等等),然后用@Subscribe注解的方法名,方法参数,执行线程,优先级这些信息构建出一个SubscriberMethod类实例,存储在FindState实例中,最后通过getMethodsAndRelease方法或者存储在FindState实例中的SubscriberMethod的list,然后释放FindState实例的引用,但是不置空FindState实例,以便下次直接使用。最终findSubscriberMethods方法就是返回了注册类中合法的@Subscribe注解方法集合,找到了便将其缓存起来并返回,如果找不到,便会抛出异常。最后看下register方法中遍历了注册类中@Subscribe注解方法构成的的SubscriberMethod的list,调用了subscribe方法。

// Must be called in synchronized block
 private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
       //拿到订阅事件类型的Class对象
        Class eventType = subscriberMethod.eventType;
        //Subscription是一个封装订阅对象和SubscriberMethod对象的封装类
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //在EventBus的subscriptionsByEventType集合中缓存订阅事件类型的Class对象对应的Subscription集合,检查订阅类是否已经注册过了
        CopyOnWriteArrayList 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);
            }
        }

        //根据优先级顺序在对应的Subscription集合中来插入本次创建的Subscription实例
        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;
            }
        }

        //在EventBus的typesBySubscriber(Map集合)中缓存订阅类中对应的订阅事件集合
        List> 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).
                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);
            }
        }
    }

总结一下这个方法主要将订阅类中的订阅事件缓存到EventBus的subscriptionsByEventType和typesBySubscriber中,以便后续发送事件使用

3、EventBus的post方法
/** Posts the given event to the event bus. */
    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;
            }
        }
    }
 
 

post方法主要是循环当前线程中保存的PostingThreadState实例中的事件队列,取出并通过postSingleEvent方法对事件进行进一步处理。

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class eventClass = event.getClass();
        boolean subscriptionFound = false;
        //是否对事件的父类也进行发送,EventBusBuilder中默认为true
        if (eventInheritance) {
            //寻找其继承关系,将其父类,以及父类的父类等也添加到eventTypesCache集合中,
            // // 返回的eventTypes集合就包含了eventClass以及eventClass的父类,父类的父类,eventClass实现的接口以及接口实现的接口等
            List> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            //遍历eventTypes中的事件,进行发送
            for (int h = 0; h < countTypes; h++) {
                Class clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            //直接对事件进行发送
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        //如果没有事件订阅者则打印日志,并发送一个NoSubscriberEvent事件
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEvent方法主要是判断是否连事件的的父类事件也要一起发送,以及对发送事件没有订阅者的情况进行处理。这里调用了postSingleEventForEventType方法来进一步处理

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
        CopyOnWriteArrayList subscriptions;
        synchronized (this) {
            //从subscriptionsByEventType集合中获取Subscription对象集合
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        //遍历订阅者集合
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    //把事件发送给订阅者
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    //还原当前线程PostingThreadState实例中的成员变量
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                //如果取消发送则跳出循环返回false
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        //没有订阅者返回false
        return false;
    }

postSingleEventForEventType方法主要是通过EventBus中的subscriptionsByEventType集合找出事件对应的Subscription对象,然后通过postToSubscription方法对订阅者和事件进行处理。

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        //判断订阅事件定义的执行线程
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING://发送事件的线程和事件执行的线程是同一线程
                //直接通过反射执行事件方法
                invokeSubscriber(subscription, event);
                break;
            case MAIN://订阅事件执行的线程是在主线程
                if (isMainThread) {
                    //当前线程是主线程,直接通过反射执行方法
                    invokeSubscriber(subscription, event);
                } else {
                    //通过主线程的handler来发送事件
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case BACKGROUND://订阅事件在后台线程执行
                if (isMainThread) {
                    //当前线程是主线程则最终通过EventBus中的executorService线程池执行事件
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    //当前线程是后台线程则直接执行事件
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC://订阅事件在别的线程异步执行
                //直接通过EventBus中的executorService线程池执行事件
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

postToSubscription方法主要是根据定义事件接收时的执行的线程,用不同的线程通过反射来执行订阅者对应的接收事件方法。
至此,post方法的流程也分析完了。接下来我们再来看EventBus的unregister方法。

4、EventBus的unregister方法
 /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        List> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class eventType : subscribedTypes) {
                //根据订阅事件来找到其对应的subscriptionsByEventType中对应的Subscription对象集合
                //从对应的订阅者集合中移除此订阅者对象
                unsubscribeByEventType(subscriber, eventType);
            }
            //从typesBySubscriber集合中移除此订阅对象以及其对应的订阅事件
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

unregister方法主要是将订阅者对象从EventBus缓存的订阅者对象以及订阅者对象订阅的方法的相关集合中移除。
至此,EvenBus整个事件的订阅,发送,执行,取消订阅我们就分析完了。大致的流程总结:

  • 订阅(register方法)时寻找订阅对象中对应的订阅事件,构建出对应的SubscriberMethod对象。将订阅对象对应的订阅事件集合缓存到EventBus中的typesBySubscriber集合中。将其订阅事件对应的Subscription对象集合缓存到subscriptionsByEventType集合中。
  • 发送(post方法)和执行,通过遍历eventTypesCache集合,找出发送事件对应的父类事件所有相关事件的集合,遍历subscriptionsByEventType集合找到订阅事件对应的Subscription对象,根据定义订阅事件所执行的线程和post方法执行的线程来进行分发事件,通过Subscription对象运用反射手段来执行订阅对象相应的订阅事件方法。
  • 取消订阅(unregister方法)主要是将订阅时缓存到typesBySubscriber和subscriptionsByEventType中订阅对象以及订阅对象的订阅事件集合进行移除。不再持有订阅对象,避免内存泄漏。

你可能感兴趣的:(EventBus源码学习笔记)