EventBus3原理分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_435559203/article/details/53075264

在接入微信支付的时候,为了传递支付结果的值,就使用了EventBus,那时候只是简单了解了EventBus的使用,现在有时间就来深入研究一下EventBus的实现原理和源码。

EventBus的介绍

可能有部分同学还没有使用过EventBus,那我们首先来了解一下EventBus的作用。
EventBus是一款基于观察者模式的事件发布/订阅框架。简化了应用程序内各组件间、组件与后台线程间的通讯。优点是开销小,优化更优雅,以及将发送者和接受者解耦。如果Activity和Activity进行交互大家都知道,而Fragment和Fragment之间通讯写法五花八门、跨线程/跨界面我们就开始头疼了,那么我们来学习一下EventBus3。

EventBus的主要三要素:

  • Event:事件。可以是任意类型的对象。
  • Subscriber:事件订阅者。在EventBus3之前消息处理通过在onEvent、onEventMainTain、onEventBackgroundThread和onEventAsync,他们代表着四种线程模型。在EventBus3之后,事件处理的方法可以按照自己需要命名,但是需要添加一个注解@Subscribe和指定线程模型。
  • Publisher:事件发布者。可以在任意线程和位置发送事件。

EventBus的四种ThreadMode

  • POSTING(默认):如果使用事件处理函数指定了线程模型为POSTING,那么该事件在哪个线程发布出来的,事件处理函数就会在这个线程中运行,也就是说发布事件和接收事件在同一个线程。在线程模型为POSTING的事件处理函数中精良避免执行耗时操作,因为它会阻塞事件的传递。
  • MAIN:事件的处理会在UI线程中执行,事件处理的时间不能太长,可能出现ANR。
  • BACKFROUND:如果事件在UI线程发布的,那么该线程就会在新的线程中运行,如果事件本来就是子线程发布的,那么该事件处理函数直接在发布事件的线程中执行,在此事件处理函数中禁止进行UI更新操作。
  • ASYNC:无论事件在哪个线程发布,该事件处理函数都会在新建的子线程中执行,同样,此事件处理函数中禁止进行UI更新操作。

EventBus的基本用法

Android Studio 配置Gradle:

compile 'org.greenrobot:eventbus:3.0.0'

定义一个事件类

public class EventBusEvent {
    private String message;

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

注册事件

EventBus.getDefault().register(this);

发送事件

EventBus.getDefault().post(message);

处理事件

扫描二维码关注公众号,回复: 4341904 查看本文章
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void XXXXXX(EventBusEvent message) {
    }

取消事件订阅

EventBus.getDefault().unregister(this);

EventBus源码分析

我们首先从开头注册开始分析EventBus.getDefault()其实就是一个单例。

    /** 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;
    }

使用双重判断方式,防止并发。接着看看 new EventBus()。

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

所在的参DEFAULT_BUILDER,在EventBus.class的全局进行初始化:

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

在看一下this调用了EventBus的另一构造方法。使用的是现在常用的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);
        ···//一系列builder赋值
    }

我们得到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);
            }
        }
    }

先是获取订阅者的class,接着交给subscriberMethodFinder.findSubscriberMethods()处理,返回的是List类型的集合,对于SubscriberMethod类中,主要是用于保存订阅方法的Method对象,线程模式、事件类型、优先级、是否是粘性事件等属性。下面我们直接看看这个方法:

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //从缓存中取出subscriberMethods,如果有则直接返回该已取的方法
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //从EventBusBuilder中可知,ignoreGeneratedIndex一般为false
        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 {
            //将获取到的subscriberMethods放入缓存中
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

首先从缓存中查找,如果缓存没有会根据ignoreGeneratedIndex选择如何查找订阅方法,ignoreGeneratedIndex默认false,可以通过EventBusBuilder来设置它的值。我们一般是通过getDefault()获取默认的EventBus对象,也就ignoreGeneratedIndex为false的情况,这时调用的是
findUsingInfo(),我们接着看看这个方法:

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        //准备一个findstate,该findState保存了订阅者类信息
        FindState findState = prepareFindState();
        //对FindState初始化
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            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这个内部类是保存订阅者的信息,我们看看它的内部结构:

    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;

        void initForSubscriber(Class<?> subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
        }
        ···
    }

可以看出,该内部类保存了订阅者及其订阅方法的信息,用Map一一对应来保存,接着利用initForSubscriber()进行初始化,在初始化的时候subscriberInfo设置为null,所以SubscriberMethodFinder的findUsingInfo()里面在初始化后会调用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) {
                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();
                            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");
            }
        }
    }

这里主要是使用了Java的反射和对注解的解析。首先是通过反射来获取订阅者中的所有方法,并根据方法的类型、参数和注解来找到订阅方法。找到订阅方法后将订阅方法相关信息保存到FindState中。

通过上述的方法,把SubscriberMethods不断逐层返回,返回到EventBus.register(),并开始遍历每一个订阅方法,并调用subscribe(subscriber, subscriberMethod)方法对所有订阅方法进行注册,那么我们接着去这方法的实现:

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        //根据订阅者和订阅方法构造一个订阅事件
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //获取当前订阅事件中的Subscription的集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        //该事件对应的Subscription的集合不存在,则重新创建并保存在subscriptionsByEventType中
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            //订阅者已经注册则抛出一个EventBusException异常
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        //遍历订阅事件,根据优先级来设置放进subscriptions,优先级高的会先被通知
        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这个Map中
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        //将当前的订阅事件添加到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);
            }
        }
    }

订阅的代码主要就是做两件事,第一件是将我们的订阅方法和订阅者封装到subscriptionsByEventType和typesBySubscriber中;subscriptionsByEventType是我们投递订阅事件的时候,就是根据我们的EventType找到我们的订阅事件,从而去分发事件,处理事件的。typesBySubscriber在调用unregister()的时候,根据订阅者找到EventType,再根据EventType找到订阅事件,从而对订阅者进行解绑。
第二件是如果是粘性事件的话,就立马执行。
这里写图片描述

分析完事件注册后,到事件发送,我们通过post方法来进行对事件的提交。接下来我们看一下post的方法:

    /** Posts the given event to the event bus. */
    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;
            }
        }
    }

代码很清晰,首先是获取一个PostingThreadState,我们看一下PostingThreadState:

    /** 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;
    }

看出该PostingThreadState封装了当前线程的信息,以及订阅者、订阅事件等。那么我们看一下怎么获取PostingThreadState的:

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

原来 currentPostingThreadState是一个ThreadLocal。我们回到post()方法里,继续是一个while循环,不断从队列中取出时间,调用postSingleEvent()。进去看一下:

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            //遍历所有事件
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        //如果没找到订阅该事件的订阅者
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

eventInheritance表示是否向上查找事件的父类,它的默认值为true,可以通过在EventBusBuilder中来进行配置。当eventInheritance为true时,则通过lookupAllEventTypes找到所有的父类事件并存在List中,然后通过postSingleEventForEventType方法对事件逐一处理,接下来看看postSingleEventForEventType方法:

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            //将该事件的event和对应的Subscription中的信息(包扩订阅者类和订阅方法)传递给postingState
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

同步取出该事件对应的subscriptions集合并遍历该集合,将事件的event和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 {
                    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);
        }
    }

根据取出的订阅方法的线程模式分别处理。这里我们根据图来理顺一下。
这里写图片描述

在我们的对应界面的生命周期中,会在onDestory()中对订阅者取消注册。那么我们来看一下unregister()方法。

    /** Unregisters the given subscriber from all event classes. */
    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());
        }
    }

typesBySubscriber我们在订阅者注册的过程中讲到过这个属性,他根据订阅者找到EventType,然后根据EventType和订阅者来得到订阅事件来对订阅者进行解绑。 看一下unsubscribeByEventType():

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

逻辑十分清晰,从从subscriptionsByEventType中获取相应的subscriptions 集合,并遍历所有的subscriptions,逐一移除。
这里写图片描述

总结:
整个EventBus是基于观察者模式而构建的,我们看一下EventBus的核心架构。
这里写图片描述
EventBus好处很明显,简化我们某些界面、线程间的通讯,实现的代码也很简单。但是由于EventBus的优点导致实现的代码可能分散得较为严重,会出现后期维护较为困难,代码的可读性大大下降。

参考:

【Bugly干货分享】老司机教你 “飙” EventBus 3

EventBus 3.0进阶:源码及其设计模式 完全解析

Android事件总线(二)EventBus3.0源码解析

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_435559203/article/details/53075264
今日推荐