美文网首页
EventBus源码分析(二)

EventBus源码分析(二)

作者: fishpan | 来源:发表于2017-04-15 21:55 被阅读42次

    前面已经说了EventBus的基本用法,下面我们一步步的看下Eventbus中到底做了些什么,为什么使用Index就让性能得到了提升。

    注册

    1、获取EventBus实例

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

    通过这种双重校验锁的方式获取单例,当然获取实例的方式还有其他方法,但是强烈建议你使用这种方式,否则你会遇到一项不到的事情。

    2、注册

    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //  查找注册类中监听的方法(通过注解或者索引)
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //  注册方法
                subscribe(subscriber, subscriberMethod);
            }
        }
    }
    

    在注册时,首先会通过SubscriberMethodFiner属性的findSubscriberMethods方法找到订阅者所有的订阅方法;然后遍历订阅方法,对统一订阅统一类型消息的方法在一个集合里;订阅类和订阅方法放在map中做一个映射,方便后边的反注册。

    3、SubscriberMethodFinder查找方法

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //  默认为false,只有指定ignoreGeneratedIndex=true才会为true
        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 {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
    
    

    SubscriberMethodFinder的findSubscriberMethods首先会通过缓存找到,找到了就返回,找不到就继续找,查找方式有两种反射和索引,主要通过ignoreGeneratedIndex,这个属性默认为false,首先进行索引找到,索引未找到时才会启动反射查找

    4、反射查找

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }
    
    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 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");
            }
        }
    }
    

    反射遍历每一个方法,然后通过注解和参数进行校验,放在FindState的subscriberMethods集合里面

    5、使用索引查找

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        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);
    }
    

    重点是在findUsingInfo里面调用了getSubscriberInfo方法,这个方法遍历调用索引的getSubscriberInfo方法,返回空则进行下一个,不为空直接返回结果。如果查找了所有的索引都没有那么会使用findUsingReflectionInSingleClass使用反射查找,那遍历的索引是在EventBusBuilder
    的addIndex方法中加入的。

    6、找到方法之后,还要进行注册,这里一步是方便后面的发布消息以及取消注册的操作

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            //  方便发送消息的操作
            subscriptionsByEventType.put(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.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
    
    }
    

    这里主要有两个Map:subscriptionsByEventType和typesBySubscriber,消息函数参数->所有的订阅方法,订阅类->订阅方法。到此EventBus的注册功能结结束了,我们来看下他的时序图

    消息发送

    1、通过调用EventBus的post方法即可完成消息的发送,在post方法中调用了postSingleEvent方法,postSingleEvent方法会继续调用postSingleEventForEventType方法

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> 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;
    }
    

    postSingleEventForEventType方法通过subscriptionsByEventType获取消息类型对应的Subscription集合,Subscription封装了实例和订阅方法名,这样我们就可以进行调用了。

    2、执行订阅方法,找到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);
        }
    }
    

    在此方法中会根据Subscription的threadMode来执行,我们最常用的就Main,我们看到如果当前是主线程会直接执行,如果不是主线程会使用mainThreadPoster,其实这是一个主进程的Handler,这也是为什么我们可以在threadMode=main的订阅方法中操作UI的原因

    3、HandlerPoster的enqueue方法,发送消息

    void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }
    

    首先这里先封装成PendingPost,然后加入队列,发送一个空的消息,为啥要这样搞呢?可能是因为直接发送一个消息过去,不方便传递Subscription和Event吧。

    4、handleMessage

    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }
    
    

    这里回去取出消息,然后再调用EvenBus的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);
        }
    }
    

    OK,在这里执行了invoke方法,订阅方法被调用了。

    EventBus反注册

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

    包括一下几个步骤:
    1、找到订阅类订阅的消息类型
    2、遍历消息类型,找到消息类型对应的所有的订阅方法
    3、遍历所有订阅方法,如果实例等于这个反注册的订阅类的进行去除操作(unsubscribeByEventType方法)
    4、去除订阅类到订阅消息类型的映射

    在使用EventBus过程中,一定要取消订阅,否则会导致内存泄漏。

    相关文章

      网友评论

          本文标题:EventBus源码分析(二)

          本文链接:https://www.haomeiwen.com/subject/pfeoattx.html