Eventbus3架构概要分析

本文分析了EventBus3的工作原理及其实现逻辑,重点介绍了如何在编译期间使用apt工具解析@Subscribe注解,以及如何在运行时调度事件响应方法。

Eventbus3概要分析

网络上对Eventbus3分析的文章已经不少了,将不对Eventbus3的具体实现进行说明,只对理解第三方插件和使用时调用的逻辑和顺序进行分析。


Androidstudio中使用EventBus3配置:
buildscript {//项目根目录中引用apt工具,使用该工具在编译时生成中间代码
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
在module gradle中应用全局的apt库:
apply plugin: 'com.neenbedankt.android-apt'
android {
应用EventBus3的解析库:
   compile 'de.greenrobot:eventbus:3.0.0-beta1'//提供注解类,和管理工具
   compile 'de.greenrobot:eventbus-annotation-processor:3.0.0-beta1' :在编译时对eventBus的注解进行解析的库
对上面的库的作用请参考: 模拟apt的处理过程 文档中使用简单的案例,说明了apt 的原理进行解析

下面对Eventbus3做一个概要的分析,主要是建立实现逻辑,这样方便在以后的开发中使用EventBus3时出现错误,能够快速找到解决问题的入手点,同时方便我们在后续的开发中用一个编码是做一个功能模块时或架构时的一个参考, 所以不会对实现的具体细节解析分析,只提供一种思想,可以使用在不同的语言中

当我们在编译项目时,apt工具会解析注入框架的类中使用@Subscribe标注的方法解析出来保存在阻塞队列中,图中标注1、2的步骤,当有事件触发时就会从队列中找出响应的方法来调用,使用反射中的invoke来执行方法。下面是代码核心的实现逻辑。

eventbus3的是建立在apt(Annotation process tools)注解解析工具这时,也就是使用在运行时对注解的解析提前到了编译期
当编译apk时,apt工具会对*.class文件进行解析,此时注解处理工具工具就会对字节码进行扫描,找到类中方法上使用了@Subscribe注解的方法,进行保存在map中
public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        // @Subscribe in anonymous classes is invisible to annotation processing, always fall back to reflection
        boolean forceReflection = subscriberClass.isAnonymousClass();
        List<SubscriberMethod> subscriberMethods =
                subscriberMethodFinder.findSubscriberMethods(subscriberClass, forceReflection);
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
当我们是用EventBus.getDefault().register(this);注册时,EventBus3会使用当前的类的字节码来读取当前类中使用了@Subscribe(threadMode = ThreadMode.MainThread)注解的方法,并且保存在map中。
private List<SubscriberMethod> findSubscriberMethodsWithReflection(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<SubscriberMethod>();
        Class<?> clazz = subscriberClass;
        HashSet<String> eventTypesFound = new HashSet<String>();
        StringBuilder methodKeyBuilder = new StringBuilder();
        while (clazz != null) {
            String name = clazz.getName();
            if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
                // Skip system classes, this just degrades performance
                break;
            }

            // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {//使用循环遍历类中的所有方法查找使用@Subscribe标记的方法
                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) {
                            String methodName = method.getName();
                            Class<?> eventType = parameterTypes[0];
                            methodKeyBuilder.setLength(0);
                            methodKeyBuilder.append(methodName);
                            methodKeyBuilder.append('>').append(eventType.getName());

                            String methodKey = methodKeyBuilder.toString();
                            if (eventTypesFound.add(methodKey)) {
                                // Only add if not already found in a sub class
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                subscriberMethods.add(new SubscriberMethod(method/*方法名称*/, eventType/*事件类型*/, threadMode/*线程模式*/,
                                        subscribeAnnotation.priority()/*优先级*/, subscribeAnnotation.sticky()/*黏性事件*/));//需要保存的信息
                            }
                        }
                    } else if (strictMethodVerification) {
                        if (method.isAnnotationPresent(Subscribe.class)) {
                            String methodName = name + "." + method.getName();
                            throw new EventBusException("@Subscribe method " + methodName +
                                    "must have exactly 1 parameter but has " + parameterTypes.length);
                        }
                    }
                } else if (strictMethodVerification) {
                    if (method.isAnnotationPresent(Subscribe.class)) {
                        String methodName = name + "." + method.getName();
                        throw new EventBusException(methodName +
                                " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
                    }

                }
            }

            clazz = clazz.getSuperclass();
        }
        return subscriberMethods;
    }


保存解析到的事件的阻塞队列中
    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<Subscription>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
        // subscriberMethod.method.setAccessible(true);

        // Got to synchronize to avoid shifted positions when adding/removing concurrently
        synchronized (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<Class<?>>();
            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<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);
            }
        }
    }

当有时间发生时,把事件存储到阻塞队列中
/** Posts the given event to the event bus. */
    public void post(Object event) {
        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;
            }
        }
    }


队列使用了生产者/消费者模式,当开始编译时包类中的所有使用@Subscribe标记的方法全部遍历出来全部添加到阻塞队列中,队列中保存用类对象的引用,不同事件标记的方法,构成消费者的队列,此时,队列处于阻塞模式,当有新消息产生时,阻塞队列有数据,就会开发查找保存过的@Subscribe的事件查找出来
    /** Looks up all Class objects including super classes and interfaces. Should also work for interfaces. */
    private List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
        synchronized (eventTypesCache) {
            List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
            if (eventTypes == null) {
                eventTypes = new ArrayList<Class<?>>();
                Class<?> clazz = eventClass;
                while (clazz != null) {
                    eventTypes.add(clazz);
                    addInterfaces(eventTypes, clazz.getInterfaces());
                    clazz = clazz.getSuperclass();
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }

查找到需要响应的@Subscribe标记的方法,通过事件类型(也就是方法的参数和EventBus.getDefault().post(user);投递的数据类型相同的方法)相同的方法来响应当前的事件,此时应为事件还要考虑在不同的线程中去处理:@Subscribe(threadMode = ThreadMode.MainThread),不同的线程是在@Subscribe声明时添加进去,并保持
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case PostThread://投递线程中调用方法
                invokeSubscriber(subscription, event);
                break;
            case MainThread://主线程中调用方法
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case BackgroundThread:非主线程中调用方法
                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);
        }
    }

当找到合适的线程去执行当前的方法后,这个时候就会想要去调用方法:
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);
        }
    }

没一个使用@Subscribe标记的方法在EventBus中保存注解信息
final class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;
    final int priority;
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;

看到这是我们就解释通了使用
@Subscribe(threadMode = ThreadMode.MainThread,priority = 100,sticky = true)
    public void onLoginEvent(String login) {
上面的代码是不是就可以找到了我们使用时不同的变量在实现时对应的实现

上面是对EventBus设计的一个概要分析,并非是对实现的细节解析分析,相关详细的分析网络上的太多,多多利用浏览器,就可以解决了

开源框架apt技术源码解析



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值