美文网首页
EventBus的原理

EventBus的原理

作者: 方言_3847 | 来源:发表于2021-02-01 16:03 被阅读0次

    小知识

    观察者模式 :定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖它的对象都会得到通知并自动更新。三个角色:
    1.Subject:就是“被观察”的角色,它将所有观察者对象的引用保存在一个集合中。
    2.Observer:是抽象的“观察”角色,它定义了一个更新接口,使得在被观察者状态发生改变时通知自己。
    3.ConcreteObserver:具体的观察者。

    承接上一篇基本用法的例子来理解这三个角色,其实就是Subject(被观察者)是考试中班里的那个优生,订阅的方法就是提前和人家打好招呼,写完了答案发过来。ConcreteObserve(观察者)就是提前和大神说好的我们这些考试等答案的人。大神做完一条短信发给众多同学,这就是一个发布过程。
    这个设计模式也是为了实现上一篇的小知识 解耦。
    书归正传。。。

    原理图

    这是EventBus的官方原理图,抄一下


    image.png

    这就是个流程图 流程图也可以大概看出 这里使用的是观察者模式。
    Publisher就是那个大神,我们就是那些Subscriber。这些Event就是答案。

    看下源码

    注解 @Subscribe

    package org.greenrobot.eventbus;
    
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface Subscribe {
        ThreadMode threadMode() default ThreadMode.POSTING;
    
        /**
         * If true, delivers the most recent sticky event (posted with
         * {@link EventBus#postSticky(Object)}) to this subscriber (if event available).
         */
        boolean sticky() default false;
    
        /** Subscriber priority to influence the order of event delivery.
         * Within the same delivery thread ({@link ThreadMode}), higher priority subscribers will receive events before
         * others with a lower priority. The default priority is 0. Note: the priority does *NOT* affect the order of
         * delivery among subscribers with different {@link ThreadMode}s! */
        int priority() default 0;
    }
    
    

    ThreadMode threadMode() default ThreadMode.POSTING;

    很直接 设置默认的模式为POSTING,这个上篇的例子讲过,就是接收答案的那些人和大神在一个教室(接收者和发布者在一个线程中)。

    boolean sticky() default false;

    设置粘性事件开关默认为false,就是我默认还没有注册的情况下不先接收消息。

    int priority() default 0;

    设置默认优先级为0,这个数越大优先级越高,优先级高的在同一模式下会优先收到消息。

    注册 EventBus.getDefault().register(this);

    这里先看下EventBus.getDefault()

      /** Convenience singleton for apps using a process-wide EventBus instance. */
        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;
        }
    

    我这少儿英语水平看最上面的英文也猜的出来,这是一个线程安全的单例模式。
    其实没什么特别的,跟我们平时写一个单例一样。只是里面的

    instance = EventBus.defaultInstance = new EventBus();

    需要看下:

       EventBus(EventBusBuilder builder) {
            logger = builder.getLogger();
            subscriptionsByEventType = new HashMap<>();
            typesBySubscriber = new HashMap<>();
            stickyEvents = new ConcurrentHashMap<>();
            mainThreadSupport = builder.getMainThreadSupport();
            mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
            backgroundPoster = new BackgroundPoster(this);
            asyncPoster = new AsyncPoster(this);
            indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
            subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                    builder.strictMethodVerification, builder.ignoreGeneratedIndex);
            logSubscriberExceptions = builder.logSubscriberExceptions;
            logNoSubscriberMessages = builder.logNoSubscriberMessages;
            sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
            sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
            throwSubscriberException = builder.throwSubscriberException;
            eventInheritance = builder.eventInheritance;
            executorService = builder.executorService;
        }
    
    

    这个也眼熟,其实就是初始化一些设置参数,这里使用的是构建者模式 。就和大神问你怎么传答案一样。是短信还是小抄,只要选择题还是只要最后几道大题,要能及格还是考高一点。一切满足客户需求。你不设置就是一个默认套餐,你要做一些私人定制 那就自定义:

    EventBus.builder()
            .eventInheritance(false)
            .logSubscriberExceptions(false)
            .build()
            .register(this);
    

    都商量好了那就定下来了

        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<?> subscriberClass = subscriber.getClass();

    这个好理解 拿到注册我的那个类。相当于找到一份学生名单

    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

    这个里面 SubscriberMethod 这个家伙里装的就是那些私人定制(是否黏性事件啦,线程模式啦,优先级啦),没有私人定制就是默认值。

    然后 findSubscriberMethods 方法就是在注册的那个类里寻找
    Subscribe注解、有public修饰符、一个参数的方法。相当于在这份学生名单中找到需要答案的那部分学生。

    for (SubscriberMethod subscriberMethod : subscriberMethods) {
    subscribe(subscriber, subscriberMethod);
    }

    最后遍历这些订阅了的方法 完成注册。相当于确认这些人,准备好写完答案发给他们。

    我们看下findSubscriberMethods方法 看看具体是怎么找的

      List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
            List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
            if (subscriberMethods != null) {
                return subscriberMethods;
            }
    
            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;
            }
        }
    

    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);

    这里我们看下 METHOD_CACHE

    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    就是一个存储订阅者和其中订阅方法的类,这样做应该是为了重复查找时的效率。这里就相当于将找到班级里对应需要答案的人,记下来.

    我们先看

    if (ignoreGeneratedIndex) {subscriberMethods =
    findUsingReflection(subscriberClass);
    } else {
    subscriberMethods = findUsingInfo(subscriberClass);
    }

    ignoreGeneratedIndex在这里时一个注解管理器 这个下次说

    findUsingInfo
    findUsingInfo()方法会在当前要注册的类以及其父类中查找订阅事件的方法,这里出现了一个FindState类,它是SubscriberMethodFinder的内部类,用来辅助查找订阅事件的方法,具体的查找过程在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();
                // 如果是public类型,但非abstract、static等
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    // 获得当前方法所有参数的类型
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    // 如果当前方法只有一个参数
                    if (parameterTypes.length == 1) {
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                        // 如果当前方法使用了Subscribe注解
                        if (subscribeAnnotation != null) {
                            // 得到该参数的类型
                            Class<?> eventType = parameterTypes[0];
                            // checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true
                            if (findState.checkAdd(method, eventType)) {
                                 // 得到Subscribe注解的threadMode属性值,即线程模式
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                // 创建一个SubscriberMethod对象,并添加到subscriberMethods集合
                                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");
                }
            }
        }
    

    再来看

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

    再接着就是判断,没人订阅的时候就抛出一个异常,有人订阅的时候就把这个人从名单中记到自己小本本上(METHOD_CACHE缓存中)

    注册方法

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
            // 得到当前订阅了事件的方法的参数类型
            Class<?> eventType = subscriberMethod.eventType;
            // Subscription类保存了要注册的类对象以及当前的subscriberMethod
            Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
            // subscriptionsByEventType是一个HashMap,保存了以eventType为key,Subscription对象集合为value的键值对
            // 先查找subscriptionsByEventType是否存在以当前eventType为key的值
            CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
            // 如果不存在,则创建一个subscriptions,并保存到subscriptionsByEventType
            if (subscriptions == null) {
                subscriptions = new CopyOnWriteArrayList<>();
                subscriptionsByEventType.put(eventType, subscriptions);
            } else {
                if (subscriptions.contains(newSubscription)) {
                    throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                            + eventType);
                }
            }
            // 添加上边创建的newSubscription对象到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;
                }
            }
            // typesBySubscribere也是一个HashMap,保存了以当前要注册类的对象为key,注册类中订阅事件的方法的参数类型的集合为value的键值对
            // 查找是否存在对应的参数类型集合
            List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
            // 不存在则创建一个subscribedEvents,并保存到typesBySubscriber
            if (subscribedEvents == null) {
                subscribedEvents = new ArrayList<>();
                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);
                }
            }
        }
    

    subscribe()方法主要是得到了subscriptionsByEventType、typesBySubscriber两个 HashMap。其中,发送事件的时候要用到subscriptionsByEventType来完成事件的处理。当取消 EventBus 注册的时候要用到typesBySubscriber、subscriptionsByEventType,完成相关资源的释放。

    网上这样说的居多,其实大白话就是 :
    订阅的过程是把之后要做的需要的事准备好,比如发送需要的 按照优先级排列顺序,这样发送的时候按照优先级好发送 把粘性事件的处理下 把取消注册的放到typesBySubscriber中,方便之后取消注册时处理typesBySubscriber

    取消注册

    EventBus.getDefault().unregister(this);

       /** 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 {
                logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
            }
        }
    
    

    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);

    得到当前注册类对象 对应的 订阅事件方法的参数类型 的集合;
    typesBySubscriber这个上面注册方法里刚提到说过,初始化了然后再解除订阅的时候要用,这里用到了

    for (Class<?> eventType : subscribedTypes) {
    unsubscribeByEventType(subscriber, eventType);
    }

    遍历参数类型集合,释放之前缓存的当前类中的Subscription

    typesBySubscriber.remove(subscriber);

    然后删除这个key对应的键值对儿

    logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());

    字面意思也看得出来 这个报错是之前没注册无法删除

    unsubscribeByEventType(subscriber, eventType);

    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
            // 得到当前参数类型对应的Subscription集合
            List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
            if (subscriptions != null) {
                int size = subscriptions.size();
                // 遍历Subscription集合
                for (int i = 0; i < size; i++) {
                    Subscription subscription = subscriptions.get(i);
                    // 如果当前subscription对象对应的注册类对象 和 要取消注册的注册类对象相同,则删除当前subscription对象
                    if (subscription.subscriber == subscriber) {
                        subscription.active = false;
                        subscriptions.remove(i);
                        i--;
                        size--;
                    }
                }
            }
        }
    

    删除的目的就是
    释放typesBySubscriber、subscriptionsByEventType中缓存的资源。

    发送事件

    EventBus.getDefault().post("Hello AZ!")

    post发放发送时间 源码

        /** 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 = 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 postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    这里的PostingThreadState类保存了事件队列和线程模式等信息 你是以哪种线程模式处理 并且新建了一个队列 把事件添加了进去

     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()) {
                        // 发送单个事件
                        // eventQueue.remove(0),从事件队列移除事件
                        postSingleEvent(eventQueue.remove(0), postingState);
                    }
                } finally {
                    postingState.isPosting = false;
                    postingState.isMainThread = false;
                }
            }
    

    这里就是就是判断线程,然后遍历事件 把事件通过postSingleEvent方法发送出去

    其实post发放是把消息添加到了list中 然后遍历之后通过
    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) {
                    logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
                }
                if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                        eventClass != SubscriberExceptionEvent.class) {
                    post(new NoSubscriberEvent(this, event));
                }
            }
        }
    

    其实这里也没处理 而是判断了下这个类的父类有没有接收方法,决定是否向上传递事件 然后把事件交给了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;
                    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;
        }
    

    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
    subscriptions = subscriptionsByEventType.get(eventClass);
    }

    这里是通过事件类型这个key去map里找对应的集合

    postingState.event = event;
    postingState.subscription = subscription;

    保存下来subscription 和event 之后 交给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 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);
            }
        }
    

    switch (subscription.subscriberMethod.threadMode)

    这里首先判断了一下线程模式是哪种 然后

    case POSTING:
    invokeSubscriber(subscription, event);
    break;

    如果是POSTING模式 则发送的在哪个线程 就在那个线程下处理

    case MAIN: if (isMainThread) {
    invokeSubscriber(subscription, event);
    } else {
    mainThreadPoster.enqueue(subscription, event);
    }
    break;

    如果是MAIN模式 如果在主线程就在主线程处理 如果发送者在子线程 就将事件放入消息队列 通过线程切换到主线程处理

    case BACKGROUND:

                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    // 如果在子线程发送事件,则直接在发送事件的线程通过反射处理事件
                    invokeSubscriber(subscription, event);
                }
                break;
    

    如果是BACKGROUND模式 如果发送者在主线程 则入消息队列 在子线程处理 如果发送者在子线程 则直接处理

    case ASYNC:
    asyncPoster.enqueue(subscription, event);
    break;

    如果是ASYNC模式 则将消息如消息队列 通过线程池处理

    这里的postToSubscription()方法就是根据发送者的线程和当线程模式来处理事件,处理方式有两种,一种是invokeSubscriber()方法 ,一种是进线程池处理

    进线程池处理就是把事件包装成了BackgroundPoster对象 然后BackgroundPoster类内就是一个线程池实现 然后去处理

    final class BackgroundPoster implements Runnable, Poster {
    
        private final PendingPostQueue queue;
        private final EventBus eventBus;
    
        private volatile boolean executorRunning;
    
        BackgroundPoster(EventBus eventBus) {
            this.eventBus = eventBus;
            queue = new PendingPostQueue();
        }
    
        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);
                }
            }
        }
    
        @Override
        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);
                    }
                } catch (InterruptedException e) {
                    eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
                }
            } finally {
                executorRunning = false;
            }
        }
    
    }
    

    他继承了Runnable接口 然后run里实现处理方法

    至于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.getDefault().postSticky("Hello AZ!");

    public void postSticky(Object event) {
            synchronized (stickyEvents) {
                stickyEvents.put(event.getClass(), event);
            }
            // Should be posted after it is putted, in case the subscriber wants to remove immediately
            post(event);
        }
    

    这个方法将事件类型和对应事件保存到stickyEvents中,方便后续使用;然后执行post(event)继续发送事件,这个post()方法就是之前发送的post()方法

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
            ......
            ......
            ......
            // 如果当前订阅事件的方法的Subscribe注解的sticky属性为true,即该方法可接受粘性事件
            if (subscriberMethod.sticky) {
                // 默认为true,表示是否向上查找事件的父类
                if (eventInheritance) {
                    // stickyEvents就是发送粘性事件时,保存了事件类型和对应事件
                    Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                    for (Map.Entry<Class<?>, Object> entry : entries) {
                        Class<?> candidateEventType = entry.getKey();
                        // 如果candidateEventType是eventType的子类或
                        if (eventType.isAssignableFrom(candidateEventType)) {
                            // 获得对应的事件
                            Object stickyEvent = entry.getValue();
                            // 处理粘性事件
                            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                        }
                    }
                } else {
                    Object stickyEvent = stickyEvents.get(eventType);
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        }
    

    之前的post()方法中 有执行粘性事件的
    可以看到,处理粘性事件就是在 EventBus 注册时,遍历stickyEvents,如果当前要注册的事件订阅方法是粘性的,并且该方法接收的事件类型和stickyEvents中某个事件类型相同或者是其父类,则取出stickyEvents中对应事件类型的具体事件,交给checkPostStickyEventToSubscription()处理

        private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
            if (stickyEvent != null) {
                // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
                // --> Strange corner case, which we don't take care of here.
                postToSubscription(newSubscription, stickyEvent, isMainThread());
            }
        }
    

    这个方法中 只是判断了一下粘性事件不为空的话,就调用postToSubscription()方法 postToSubscription()方法就是上面讲过的postToSubscription()方法 最终会判断线程模式将消息发送到接受方法里
    这种方式实现了在注册之前 发送了粘性事件
    最后 附上原理图

    EventBus.png

    相关文章

      网友评论

          本文标题:EventBus的原理

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