EventBus源码浅析

EventBus源码浅析

    两年多没有写博客了,这两天有时间了读读一些框架源码,用了挺长时间的EventBus了,虽然有很多大神早就分析了源码,但是还只有自己分析一遍才能有更大的收获,由于个人水平有限,如果各位看官看出解读不恰当的地方望指出,一起学习,一起成长!

此次主要从以下几个模块来介绍

1、EventBus基本使用

2、EventBus注册源码解析

3、EventBus取消注册源码解析

4、EventBus事件分发源码解析

5、EventBus原理总结

使用之前先来了解它定义了4种ThreadMode:

1,默认的threadMode:POSING
    subscribe和post在同一个线程

2,MAIN:
    subcribe永远在main线程被调用,不论post是在哪一个线程

3,BACKGROUND:
    3.1 post在子线程,subscribve就会在相同的子线程
    3.2 post在main线程,subscribe会在新开的子线程接收

4,ASYNC:
    subscribe永远和post在不同的线程,比如:post在main线程,subscribe就会在子线程,post在子线程,subscribe就会在另外一个不同
    的子线程

1,基本使用:

    1.1 先注册:EventBus.getDefault().register();
    1.2 取消注册:EventBus.getDefault().unre,gister();
    1.3 定义一个Event事件类,类似java的bean,并且在订阅者中定义@Subscribe注解方法
    1.4 发送事件:EventBus.getDefault().post();

Tips:除了根据EventBus.getDefault()获取默认的EventBus对象,还能根据建造者EventBusBuilder去配置自定义的EventBus,具体看EventBusBuilder源码

2,注册源码解析:

注册其实就是操作相关map做put操作: 

几个最为核心成员变量:

//event事件类为key,订阅列表为value,Subscription是一个封装类封装了订阅者和订阅方法的封装类
事件post以后,会在这个map中根据event来查找订阅者Subscribe
private final Map, CopyOnWriteArrayList> subscriptionsByEventType;
//以订阅者类为key,以post的event事件类为value,调用register()或者unRegister()时候会操作这个map
private final Map>> typesBySubscriber;
private final Map, Object> stickyEvents;

       EventBus源码浅析_第1张图片

这里盗用别人图借用一下!!!

先看下注册的入口: 

EventBus#register
        //params:subscriber 一般指代调用者当前所在类的对象
       public void register(Object subscriber) {
       //获取订阅者类的Class
        Class subscriberClass = subscriber.getClass();
        //根据订阅者类的Class找到它所有的的订阅方法,保存在List中
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

EventBus#subscribe

    //添加订阅的逻辑的具体实现,整个register()到此结束
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //根据订阅的某一个具体method获取其相应对应的event事件类class
        Class eventType = subscriberMethod.eventType;
        //订阅者,订阅方法封装起来
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //根据event从Map中获取所有订阅这个event的subscribe的list列表
        CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
        //这个event从来没有被任何subscrobe订阅过,这个Subscribe之前没有注册过这个事件,此时eventType--subscriptions关联一下
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
                //所有订阅该event的subscribe中,已经存在改subscribe,说明这个subscribe老爸订阅过了(不允许)
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }
        //根据优先级决定这个subscribe在订阅此event的所有subscribe的队列中的位置
        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;
            }
        }
            
        //根据subscribe获取这个它当前所有订阅的event集合
        List> subscribedEvents = typesBySubscriber.get(subscriber);
        //说明此subscribe没有订阅过这个event,此时subscriber--subscribedEvents关联下
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

            //粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                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);
            }
        }
    }

SubscriberMethodFinder#findSubscriberMethods 

    //根据订阅者查找当前订阅者所有订阅的方法
    List findSubscriberMethods(Class subscriberClass) {
        //METHOD_CACHE是一个Map, List>,在SubscriberMethodFinder 39行,根据订阅者查出它所有订阅的方法或者event
        List subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        //当没有@Subscribe这样的public方法时候抛异常
        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;
        }
    }

SubscriberMethodFinder#findUsingInfo 


//查找当前订阅者所有订阅过的方法
    private List findUsingInfo(Class subscriberClass) {
        //清空FindState缓存池
        FindState findState = prepareFindState();
        //初始化赋值相关
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //一开始订阅者信息时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);
    }

SubscriberMethodFinder#getSubscriberInfo 

//常规获取订阅者信息方式:根据Findstate的subscriberInfo字段获取订阅者信息
 private SubscriberInfo getSubscriberInfo(FindState findState) {
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

SubscriberMethodFinder#findUsingReflectionInSingleClass 

//反射获取订阅者信息方式
private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
           //获取当前类以及父类所有的public方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            //假如订阅者没有声明public方法,那就获取它当前类的所有私有和非私有的方法
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        //循环中找到Subscribe调用FindState的findState.subscriberMethods一个个add进去
        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 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");
            }
        }
    }

SubscriberMethodFinder#FindState#checkAdd和checkAddWithMethodSignature 


//允许一个类有多个参数相同的订阅方法。
boolean checkAdd(Method method, Class eventType) {
            // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
            // Usually a subscriber doesn't have methods listening to the same event type.
            Object existing = anyMethodByEventType.put(eventType, method);
            if (existing == null) {
                return true;
            } else {
                if (existing instanceof Method) {
                    if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                        // Paranoia check
                        throw new IllegalStateException();
                    }
                    // Put any non-Method object to "consume" the existing Method
                    anyMethodByEventType.put(eventType, this);
                }
                return checkAddWithMethodSignature(method, eventType);
            }
        }

        //子类继承并重写了父类的订阅方法,那么只会把子类的订阅方法添加到订阅者列表,父类的方法会忽略。
        private boolean checkAddWithMethodSignature(Method method, Class eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class methodClass = method.getDeclaringClass();
            Class methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                // Only add if not already found in a sub class
                return true;
            } else {
                // Revert the put, old class is further down the class hierarchy
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }

SubscriberMethodFinder#getMethodsAndRelease

    
    //把当前订阅者所有的订阅方法的List返回到最初register()地方,findUseringInfo()到此终结!,整个register也基本结束
   private List getMethodsAndRelease(FindState findState) {
        List subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        findState.recycle();
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        return subscriberMethods;
    }

取消注册源码分析:

取消注册其实就是操作相关map做remove操作:

EventBus#unregister

    
    //操作Map>> typesBySubscriber,订阅者--订阅event这个map,根据subscribe去remove掉他所有注册的事件
  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#unsubscribeByEventType


//操作event---subscribe这个map将这个subscribe中的所有event对应的这个subscribe移除掉
 private void unsubscribeByEventType(Object subscriber, Class eventType) {
        List 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--;
                }
            }
        }
    }

2,开始真正的表演:post触发事件传递源码分析

EventBus源码浅析_第2张图片

这里盗用别人图借用一下!!!

首先看一个event发送过程中状态的封装类:封装订阅者,订阅的event,线程信息

EventBus#PostingThreadState

    final static class PostingThreadState {
        final List eventQueue = new ArrayList();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }
     
   
  

EventBus#post

 public void post(Object event) {
 //currentPostingThreadState是一个ThreadLocal,而ThreadLocal是每个线程独享的,其数据别的线程是不能访问的,可以理解为一个线程自己独有一个线程本地变量
        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;
            }
        }
    } 
   
  

EventBus#postSingleEvent


private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            List> 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));
            }
        }
    }

EventBus#lookupAllEventTypes

    //对于一个事件,默认会找出它的父类,并且把父类也作为事件之一发送给订阅者,将event的父类的也当做event正常post
  private static List> lookupAllEventTypes(Class eventClass) {
        synchronized (eventTypesCache) {
            List> eventTypes = eventTypesCache.get(eventClass);
            if (eventTypes == null) {
                eventTypes = new ArrayList<>();
                Class clazz = eventClass;
                while (clazz != null) {
                    eventTypes.add(clazz);
                    addInterfaces(eventTypes, clazz.getInterfaces());
                    clazz = clazz.getSuperclass();
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }

EventBus#postSingleEventForEventType

 private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
        CopyOnWriteArrayList subscriptions;
        synchronized (this) {
            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 {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

EventBus#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发送message到主线程,然后由主线程利用反射回掉订阅者当初订阅的方法
                    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);
        }
    }

EventBus#invokeSubscriber

    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            //利用反射最终会调用到当初订阅者订阅的方法
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

总结:

最后我们以文字形式来总结一下EventBus的工作原理

订阅逻辑

1、首先用register()方法注册一个订阅者

2、获取该订阅者的所有订阅的方法

3、根据该订阅者的所有订阅的事件类型,将订阅者存入到每个以 事件类型为key 以所有订阅者为values的map集合中

4、然后将订阅事件添加到以订阅者为key 以订阅者所有订阅事件为values的map集合中

事件发送逻辑

1、首先获取当前线程的事件队列

2、将要发送的事件添加到事件队列中

3、根据发送事件类型获取所有的订阅者

4、根据响应方法的执行模式,在相应线程通过反射执行订阅者的订阅方法

取消逻辑

1、首先通过unregister方法拿到要取消的订阅者

2、得到该订阅者的所有订阅事件类型

3、遍历事件类型,根据每个事件类型获取到所有的订阅者集合,并从集合中删除该订阅者

4、将订阅者从步骤2的集合中移除



                                感谢大家看到最后!




你可能感兴趣的:(android)