再看EventBus之(EventBus架构、源码刨析)

网上有关EventBus的解析很多,为什么笔者要再写一次呢?第一:笔者很早以前就研究过这方面的源码,但是时间长了就忘了,所以在此用于记录;第二:网上很多写的EventBus模式源码介绍都不对,所以笔者在此纠正一下,大家共勉学习一下。

第一:EventBus这个类采用了外观模式(也就是门面模式,用户只要通过EventBus操作所有的功能,而没有必要直接和里面的子功能的类打交道,也就是说EventBus提供简单易用的接口给客户端使用)。

第二:EventBus的获取采用了双doube检测的单例模式

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

第三:EventBus这个类在默认构造的时候,由于参数比较多,并且需要调用端了解参数的细节所以采用了构造者模式

  public EventBus() {
        this(DEFAULT_BUILDER);
    }
 

其中DEFAULT_BUILDER是EventBusBuilder类

public class EventBusBuilder {
    private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();

    boolean logSubscriberExceptions = true;
    boolean logNoSubscriberMessages = true;
    boolean sendSubscriberExceptionEvent = true;
    boolean sendNoSubscriberEvent = true;
    //是否发送订阅异常
    boolean throwSubscriberException;
    boolean eventInheritance = true;
    //是否忽路索引默认为false
    boolean ignoreGeneratedIndex;
    boolean strictMethodVerification;
    //默认线程池执行类
    ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
    List<Class<?>> skipMethodVerificationForClasses;
    //采用编译时期注解将订阅者加入集合
    List<SubscriberInfoIndex> subscriberInfoIndexes;
    Logger logger;
    //主线程操作模式类
    MainThreadSupport mainThreadSupport;

    EventBusBuilder() {
    }

这个类就相当于给EventBus使用前的默认配置的属性,例如需要使用线程池来异步操作发布订阅事件、查订阅者的工具类、主线程操作策略类等等;先来看看主线程操作的类MainThreadSupport的实现

 class AndroidHandlerMainThreadSupport implements MainThreadSupport {

        private final Looper looper;

        public AndroidHandlerMainThreadSupport(Looper looper) {
            this.looper = looper;
        }

        @Override
        public boolean isMainThread() {
            return looper == Looper.myLooper();
        }

        @Override
        public Poster createPoster(EventBus eventBus) {
            return new HandlerPoster(eventBus, looper, 10);
        }
    }

可以看出MainThreadSupport只是处在一个中介的地位,而真正进行主线程操作的类是HandlerPoster

public class HandlerPoster extends Handler implements Poster

HandlerPoster继承与Hander,所以切换到主线程通信最终还是用的Hander消息队列。而这里传来的Loop是UI线程Loop,如下:

 Object getAndroidMainLooperOrNull() {
        try {
            return Looper.getMainLooper();
        } catch (RuntimeException e) {
            // Not really a functional Android (e.g. "Stub!" maven dependencies)
            return null;
        }
    }

所以没有毛病。

第四:观察者模式订阅者,EventBus注册的时候会把订阅者保存到集合中,而在发布事件的时候根据事件的Class类型从集合中找到相应事件然后进行分发事件;接着来看一看注册方法

 public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //通过subscriberMethodFinder查找所有当前的类的所有注册方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            //遍历所有的方法
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

首先通过注册对象的class用subscriberMethodFinder查找类得到所有的注册方法:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //采用享元模式将注册事件保存到METHOD_CACHE缓存中
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
//默认为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 {
            //将订阅者class放入缓存中(它所订阅的所有的方法)
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

这里又用到了享元模式(经常使用的对象保存以内存换速度),将注册事件方法存入METHOD_CACHE,中省的每次都去重新构建浪费时间,如果缓存集合中没有的话就会调用findUsingReflection或findUsingInfo去查到数据然后将它们放入集合中;首先来看findUsingReflection

 private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        //创建查找状态类FindState或从缓冲池里找又用到享元模式
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

这里创建查找状态类又用到享元模式,最终的查找是findUsingReflectionInSingleClass,利用While循环是想把当前类和它所继承的所有超类注解都查询出来,免得遗漏。

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

利用反射将当前订阅者类的所有方法都遍历出来,把满足要求的方法(是public,就一个参数,并且有Subscribe注解的方法)则将注解解析出来放进subscriberMethods集合并返回。

而findUsingInfo方法和这个实现第一个方法实现类似,唯一区别就是检查索引集合中是否有注册事件(注解的时候创建的集合需要手动代码添加);最终调用subscribe将真正的订阅者包装类Subscription以当前注册对象和SubscriberMethod绑定放到集合中,随后判断当前事件是否是粘性事件,如果是的话检测一下它是否要执行一次事件。

第五:观察者模式发布者:从post方法入手,如下:

public void post(Object event) {
        //可以在子线程初始化
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //将事件加入eventQueue
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            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是线程私有类

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

首先将事件参数对象加入eventQueue集合中,随后,循环开始执行集合中的事件,由于集合属于线程私有,所以同一个线程执行是串行任务,不同线程发布事件不会彼此影响事件的发布。继续:

 private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;

        //根据参数类型查找订阅事件调用postSingleEventForEventType执行
        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) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

这个方法首先根据参数配置eventInheritance参数配置(默认为true),将所有的事件参数类型的父类型遍历出来,一块执行,最终通过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;
    }

该方法就是根据事件参数类型查出所有符合条件的方法来进行事件发布,调用postToSubscription方法。

第六部:策略模式

 private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        //四种模式默认是ThreadMode.POSTING
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                //直接调用反射
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    //直接调用反射
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(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);
        }

这个方法是真正实现订阅者注册方法调用的,总共有五中执行策略,默认是POSTING,也就是你在注解方法的时候添加的,如:

@Subscribe(threadMode = ThreadMode.MAIN)

如果不声明默认是POSTING模式直接执行反射订阅者方法调用:

  if (isMainThread) {
                    //直接调用反射
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }

MAIN模式(会在UI线程中执行反射调用):


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

如果是主线程直接反射执行,否则用策略类mainThreadPoster(实现类是HandlerPoster,就是实现了Handler)执行。

MAIN_ORDERED模式:(UI线程顺序执行事件的反射调用调用,利用了消息队列先进先出的原则)执行用mainThreadPoster发消息处理。

BACKGROUND模式:(在后台线程同步执行消息的处理),用了策略类backgroundPoster

 public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this);
            }
        }
    }

可以看见这里向队列添加执行事件加了锁,它和取数据是互斥的

 public void run() {
        try {
            try {
                while (true) {
                    PendingPost pendingPost = queue.poll(1000);
                    if (pendingPost == null) {
                        synchronized (this) {
                            // Check again, this time in synchronized
                            pendingPost = queue.poll();
                            if (pendingPost == null) {
                                executorRunning = false;
                                return;
                            }
                        }
                    }
                    eventBus.invokeSubscriber(pendingPost);
                }
 synchronized PendingPost poll(int maxMillisToWait) throws InterruptedException {
        if (head == null) {
            wait(maxMillisToWait);
        }
        return poll();
    }

 eventBus.getExecutorService().execute在同一时间只会执行一次,就是说你同时利用此模式发送了多个事件,则事件的处理会在子线程串行执行(同步的)。

ASYNC模式:(在后台线程异步执行消息的处理)它的实现策略类是AsyncPoster

 public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

可以看到,每次执行事件调用前都直接执行 eventBus.getExecutorService().execute,所以说事件最后的调用是异步调用。

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值