EventBus3.0源码分析

构造函数

EventBus.getDefault().register(this);

首先getDefault()的方法

static volatile EventBus defaultInstance;
 /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

关键字:volatile 防止指令排序错乱
单例模式–双重锁模式的单例,所以eventbus通信只能在相同进程中。
往下看new EventBus();

EventBus(EventBusBuilder builder) {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        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;
    }

建造者模式的builder类初始化
这个subscriptionsByEventType存储event类型的缓存集合
stickyEvents粘性事件的集合
mainThreadPoster主线程的发送者, 它的实现HandlerPoster是直接继承HandlerHandler的回调是在主线程的。new HandlerPoster(this, Looper.getMainLooper(), 10);maxMillisInsideHandleMessage参数为啥是10?因为在主线程中handle处理一条消息超过10秒会ANR。所以在HandlerPoster中做了异常处理:

if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
   }

backgroundPoster 后台线程的发送者,实现了Runnable接口;继承Runnable的异步线程处理类,将订阅函数的执行通过Executor和队列机制在后台一个一个的执行
asyncPoster异步线程的发送者,实现了Runnable接口
indexCountList<SubscriberInfoIndex> subscriberInfoIndexes;的size值;所以就要明白SubscriberInfoIndex是干嘛的!
SubscriberInfoIndex是编译期间通过注解处理器生成的一个类,其中存储了Subscriber以及相关SubscriberMethod。
subscriberMethodFinder订阅者响应函数信息存储和查找类,参考构造方法参数,携带 List<SubscriberInfoIndex>ignoreGeneratedIndex 即使有生成的索引,也强制使用反射,默认为false。

注册

首先记住凡是注册的订阅者接受事件后,再被销毁或者不在接受时需要手动去注销订阅。

 public void register(Object subscriber) {
 		//当前订阅者
        Class<?> subscriberClass = subscriber.getClass();
        //订阅者响应函数信息存储和查找类去查找 当前订阅者 所关联的订阅函数
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

findSubscriberMethods函数

private static final Map<Class<?>, List<SubscriberMethod>>
 METHOD_CACHE = new ConcurrentHashMap<>();
 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
 //METHOD_CACHE  缓存 的一个map集合,先查找缓存是否有对应的subscriberClass
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
		//没有在缓存中找到
		//ignoreGeneratedIndex 即使有生成的索引,也强制使用反射
		// 默认为false 先看findUsingInfo方法  
        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;
        }
    }
private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                	//保证状态被使用后,对应的对象池维护的队列的元素,要重制为开始状态,对于下一个客户端使用时,不能是FindState处于不可预期状态(简单对象池模式)
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        //全为null,空对象池,需要新new出来一个
        return new FindState();
    }
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
		//对象池,防止多次创建,造成内存浪费
        FindState findState = prepareFindState();
        //初始化findState
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
        	//getSubscriberInfo 核心思想之一  后面讲  先看为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);
    }
subscriberInfo为null情况

会走findUsingReflectionInSingleClass方法,如下

 private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            //官方先说的是 getDeclaredMethods速度比getMethods快
            //getMethods某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
            // getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。
            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) {
        //getModifiers()方法返回int类型值表示该字段的修饰符
        //PUBLIC: 1  PRIVATE: 2  PROTECTED: 4  STATIC: 8  FINAL: 16
            int modifiers = method.getModifiers();
            //这里注意:所以订阅的方法必须是public的
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            //获取参数类型
                Class<?>[] parameterTypes = method.getParameterTypes();
                //规定了订阅方法参数长度为1
                if (parameterTypes.length == 1) {
                //获取方法注解
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        //校验参数
                        if (findState.checkAdd(method, eventType)) {
                        //threadMode 就是eventbus提供的几种线程切换 参考`Subscribe`
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            //然后添加到subscriberMethods集合中
                            //SubscriberMethod是个订阅方法的包装参数类,包括(方法,参数,线程模式,优先级,是否粘性)。
                            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");
            }
        }
    }

总结下findUsingReflectionInSingleClass就干了一件事:找到当前订阅者中订阅方法,保存在findState中。

subscriberInfo不为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);
                    }
                }
            }

再回到findUsingInfo中最后调用return getMethodsAndRelease(findState);方法,会放回最后需要的List<SubscriberMethod>

  private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
  //就是拿到findState中再`findUsingReflectionInSingleClass`保存的subscriberMethods返回,然后重置下findState
        List<SubscriberMethod> 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;
    }

最后回到findSubscriberMethods方法,再回到register方法中:往下看,
会依次订阅 当前订阅者 和 订阅者类中的方法。

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

具体看下subscribe方法

 private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        //Subscription 当前订阅者 和 订阅方法 的包装类
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //subscriptionsByEventType是构造函数中,存储event类型的缓存集合。就是该订阅方法入参的event实体类。不懂回看findUsingReflectionInSingleClass方法。
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            //没有找到,存入新的到subscriptionsByEventType中
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
        //重复注册的会在这里抛错
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        //找到事件的优先级比他小的,插入到subscriptions
        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);
		//立即处理粘性事件的
		//粘性事件后面再讲
        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);
            }
        }
    }

整个注册方法下来,就是将当前订阅者 和 订阅方法(按照优先级顺序) 存入到一个集合中,再有粘性事件时就去处理粘性事件。

post事件

/** Posts the given event to the event bus. 
发送事件到总线*/
    public void post(Object event) {
    	//PostingThreadState中保存着事件队列信息和线程信息
    	//ThreadLocal使用,保护数据
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //加入事件队列
        eventQueue.add(event);

        if (!postingState.isPosting) {
        	//判断looper == Looper.myLooper()
            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;
            }
        }
    }

首先获取posting状态,将当前最新状态赋值给PostingThreadState,然后调用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;
        //获取事件对应的 subscriptions
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
          //遍历Subscription
            for (Subscription subscription : subscriptions) {
              //把事件的event和对应的Subscription中的信息(包扩订阅者类和订阅方法)传递给postingState
                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;
    }

会依次取出subscription中再注册时候保存的订阅者和订阅者方法,赋值给postingState的subscription,然后再调用postToSubscription方法。

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
//根据Subscription中订阅方法指定的线程类型,分开处理
        switch (subscription.subscriberMethod.threadMode) {
        /**
     * 与发送事件同一个线程
     * 注意:如果post在主线程,避免在订阅方法中做耗时操作
     */	
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
                 /**
     * 主线程
     * 如果post在主线程,事件会直接主线程,会堵塞发布线程
     * 如果post在子线程,则会排队等待,使用handle回调在主线程
     */	
            case MAIN:
           
                if (isMainThread) {
                	//都在主线程,直接执行方法
                    invokeSubscriber(subscription, event);
                } else {
                	//post在子线程下,会将`PendingPost`加入队列中,然后需要`HandlerPoster`发送消息,依次去处理队列消息。
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
               /**
     * 主线程-排队
     * 不同于MAIN,此模式事件总是排队等待传递,不会阻塞发布线程
     */	 
            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;
                /**
     * 后台线程
     * 如果post在子线程,则在post所在的线程执行
     * 如果post是主线程,则使用单个后台线程按顺序执行
     */	
            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);
        }
    }

看具体每个方法

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);
        }
    }
mainThreadPoster.enqueue(subscription, event)

mainThreadPoster是构造函数中初始化的发布队列

 mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;

最终是创建的是new HandlerPoster(eventBus, looper, 10);

maxMillisInsideHandleMessage:最大处理时间,默认为10,超过会重新调度

public void enqueue(Subscription subscription, Object event) {
		//获取当前等待的post
        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");
                }
            }
        }
    }
 static PendingPost obtainPendingPost(Subscription subscription, Object event) {
        synchronized (pendingPostPool) {
        	//从对象池拿个对象出来
            int size = pendingPostPool.size();
            if (size > 0) {
                PendingPost pendingPost = pendingPostPool.remove(size - 1);
                pendingPost.event = event;
                pendingPost.subscription = subscription;
                pendingPost.next = null;
                return pendingPost;
            }
        }
        //没有,就创建一个
        return new PendingPost(event, subscription);
    }

轮询会调用handleMessage方法

 @Override
    public void handleMessage(Message msg) {
    
        boolean rescheduled = false;
        try {
        	//获取时间间隔;started开始时间
            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;
                        }
                    }
                }
                //调用invokeSubscriber
                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;
        }
    }
 void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

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

backgroundPoster.enqueue(subscription, event)

在构造方法中初始化backgroundPoster = new BackgroundPoster(this),是直接实现了Runnable接口.

 public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            //是否有任务在执行
            if (!executorRunning) {
                executorRunning = true;
                //执行run方法
                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;
                            }
                        }
                    }
                    //执行invokeSubscriber
                    eventBus.invokeSubscriber(pendingPost);
                }
            } catch (InterruptedException e) {
                eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
        //置回标志位
            executorRunning = false;
        }
    }
asyncPoster.enqueue(subscription, event)

在构造方法里初始化的asyncPoster = new AsyncPoster(this);,同BackgroundPoster一样实现了Runnable接口。

 public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        //直接执行,不会有等待,会新开一个线程去处理
        eventBus.getExecutorService().execute(this);
    }

    @Override
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        //直接执行反射调用事件方法
        eventBus.invokeSubscriber(pendingPost);
    }
粘性事件的处理

前面说到的粘性事件处理,会最终还是调用postToSubscription,就是处理时机不同,粘性事件可以先post,再注册。因为在注册的时候,如果当前事件集合中存在粘性事件,会立即去执行postToSubscription方法。而非粘性事件必须需要先注册,再等待post事件来触发订阅事件。

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

解绑

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

 /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> 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--;
                }
            }
        }
    }

总结

这是官网给出的eventbus的架构图,就是观察者模式。用少量的代码帮忙解偶合,而且在3.0后可以采用编译时注解来替代反射方案,性能上也没以前消耗那么大。但是,eventbus的单事件模式(一个订阅方法对应一个事件实体类)会造成有大量的event事件实体类,而且订阅方法分散在各个类中。优化:事件实体类可以维护在一个包下,可以根据视图业务再去分包管理;可以使用eventbus3.0插件eventbus3-intellij-plugin更方便的找到订阅者和事件发送的关联位置。在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值