EventBus 源码分析

           俗话说,好记性不如烂笔头。特别是程序这一块,你自己不动手敲敲永远感觉迷迷糊糊的,所以,我们在学习一个新知识点的时候,首先要知道它怎么用,然后还要去研究它为什么这么用,即它里面的原理到底是什么样子的。关于EventBus,我想就不用去说怎么用了,因为它用起来确实很方便。但是,如果我问你,你真的懂EventBus吗?你知道里面用到了哪些设计模式吗?可能很多人会一脸懵逼状态,不要怕,下面我们就一起来看看吧!

        1. 什么是EventBus

                  EventBus是由greenrobot组织贡献(该组织还贡献了greenDAO),一个Android事件发布/订阅轻量级框架;

                  通过解耦发布者和订阅者简化Android事件传递

                  EventBus可以代替Android传统的Intent,Handler,Broadcast或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法。代码简洁,是一种发布订阅设计模式(观察者设计模式)

 

        2. EventBus三要素

                 既然EventBus用的是设计者观察者模式,那么肯定具备观察者设计模式的三要素(观察者,被观察者,事件),那么在EventBus中对应的就是Event事件(可以是任意对象),Subscriber 事件订阅者,Publisher 事件的发布者

            1.Event:

                     可以是任何事件

            2.Subscriber :

                     在EventBus3.0之前我们必须定义以onEvent开头的那几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe(),并且指定线程模型,默认是POSTING

            3.Publisher :

                     我们可以在任意线程里发布事件,一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。

         3. EventBus线程模型

                  既然EventBus可以在任意地方发布事件,那么也就意味着EventBus内部对线程进行了处理。EventBus线程模型共有四种:

              1.POSTING:

                 事件的处理和事件的发送在相同的进程,所以事件处理时间不应太长,不然影响事件的发送线程,而这个线程可能是UI线程

              2.MAIN

                 事件的处理会在UI线程中执行,事件处理不应太长时间

              3.MAIN_ORDERED

                 事件的处理会在UI线程中执行,不过需要排队,如果前一个也是main_ordered 需要等前一个执行完成后才执行,在主线程中执行,可以处理更新ui的操作。不过需要排队,如果前一个也是main_ordered 需要等前一个执行完成后才执行,在主线程中执行,可以处理更新ui的操作。

              4.BACKGROUND

                 事件的处理会在一个后台线程中执行,尽管是在后台线程中运行,事件处理时间不应太长。如果事件分发在主线程,事件会被加到一个队列中,由一个线程依次处理这些事件,如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。如果事件分发在后台线程,事件会立即执行处理。

              5.ASYNC 

                 事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,每个事件会开启一个线程(有线程池)

              

      前面的这些都是铺垫,现在才开始进入主菜,Are you ready?

        先贴出一个简单的使用的例子

class GuideActivity : BaseActivity() {

    private lateinit var mProgress: MyProgressBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guide)
        EventBus.getDefault().register(this)
        initView()
        initData()
    }

    private fun initView() {
        mProgress = findViewById(R.id.progress)
    }

    private fun initData() {
        mProgress.start(3000)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun messageEventBus(messageEvent: MessageEvent){
        startActivity(Intent(this, SplashActivity::class.java))
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }
}

  我们第一个要研究的方法就是EventBus.getDefault.register(this);

 // 在这里我们以GuideActivity来进行分析
  public void register(Object subscriber) {
        // 在我们注册的时候subscriber就是我们传递进来的GuideActivity,即:subscriber = GuideActivity
        // 获取传递进来的事件订阅者的类名 subscriberClass = GuideActivity.class
        Class<?> subscriberClass = subscriber.getClass();
        // SubscriberMethod:用来存放事件订阅者的一些基本信息(包括Method,ThreadMode,EventType,Priority,sticky)
        // 通过事件订阅者的类名来找到该类中标记为Subscribe的方法,并把该方法的所有信息封装成SubscriberMethod对象
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                // 遍历循环每一个SubscriberMethod
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

 接下来我们看看findSubscriberMethods()里面到底是做了一些什么操作

 

########################################### SubscriberMethodFinder ################################
    private final boolean ignoreGeneratedIndex;

    private static final int POOL_SIZE = 4;
    private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];

    SubscriberMethodFinder(List<SubscriberInfoIndex> subscriberInfoIndexes, boolean strictMethodVerification,
                           boolean ignoreGeneratedIndex) {
        this.subscriberInfoIndexes = subscriberInfoIndexes;
        this.strictMethodVerification = strictMethodVerification;
        this.ignoreGeneratedIndex = ignoreGeneratedIndex;
    }
    
    
    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // METHOD_CACHE是啥?在上面找到这个
        // private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
        // 看到这里我们就懂了,原来METHOD_CACHE是一个集合,一个以Class<?>为key,一个List<SubscriberMethod>为value的值的map集合
        // 第一次的时候肯定是空的,所以我们走下面的,第二次的话直接从缓存里面读取,然后直接返回,从而避免了通过反射再次去拿取
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // ignoreGeneratedIndex是啥?从上面可知是在构造函数里面赋值的,那么SubscriberMethodFinder是在哪里被实例化的呢?
        // 原来是在EventBus的构造函数里面被实例化的,为了方便,我在下面直接贴出来了
        // 而最终的赋值是在EventBusBuilder里面,而默认是false,所以走下面的findUsingInfo
        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        // 当subscriberMethods为空的时候,会抛出一个异常,其实到这里我们就明白了,
        // 凡是被register()的类必须要有事件订阅者,即有被@Subscribe标注的方法
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            // 当subscriberMethods不为空的时候,直接添加到集合里面,然后返回
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
        
        // 那么在findUsingInfo里面又做了哪些事情呢?
    }
    
    ########################################### 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;
    }

​

那么在findUsingInfo里面又做了哪些事情呢?

          

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        // FindState又是啥?不要急,我们慢慢来看
        // 我们看单词意思来猜一下,这个应该是保存传递过来的GuideActivity.class类里面被标注为@Subscribe方法的信息的实体类
        // 点进去看一下,哈哈哈,看了下面的代码是不是恍然大悟,原来真的是这样
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 当Guide.class不为空的时候,拿取对应的信息并返回
            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 {
                // 当Guide.class为空的时候,拿取对应的信息并返回
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        // 返回List<SubscriberMethod>集合
        return getMethodsAndRelease(findState);
    }
    
    ########################################## FindState ##############################
    static class FindState {
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class<?> subscriberClass;
        Class<?> clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;

        void initForSubscriber(Class<?> subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
    }

 

// 关键代码来了
private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            // 找到GuideActivity.class的所有方法
            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
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                // 拿到方法参数,即如果你是写的String message,那么拿到的值就是String.class
                Class<?>[] parameterTypes = method.getParameterTypes();
                // 只允许带一个参数
                if (parameterTypes.length == 1) {
                    // 拿到注解为Subscribe
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        // 拿到注解为Subscribe里面的参数信息
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 将所有的参数信息封装成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");
            }
        }
}

别急哈,上面的分析才只是分析了这行代码

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

接下来我们继续向下走,分析这行代码

subscribe(subscriber, subscriberMethod);

注意这里面带了两个参数:subscriber其实是GuideActivity.class,subscriberMethod就是被标记为@Subscribe方法的所有信息组合起来的实例SubscriberMethod。

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 拿到对应的类型,注意这里的eventType应该是String.class,而不是GuideActivity.class,千万别搞混了
        Class<?> eventType = subscriberMethod.eventType;
        // 这里的Subscription又是啥呢?点进去看看
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // subscriptionsByEventType是一个集合,用来保存以Class为key,以CopyOnWriteArrayList<Subscription>为value的集合
        // 注意这里的key是方法里面的参数类型,即String
        // 所以这里的key是String.class等等
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        // 第一次为空
        if (subscriptions == null) {
            // 实例化集合
            subscriptions = new CopyOnWriteArrayList<>();
            // 将数据添加到Map集合中
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            // 当不为空的时候且集合里面有这个值,就抛出异常
            // 不信的同学可以在同一个类里面注册两次试试哦,看会不会抛出这个异常
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        // 根据优先级进行排序  
        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;
            }
        }

        // 这里又来一个集合,这个集合是干吗的呢?
        // 从上面可以推导出subscriber==GuideActivity.class
        // 所以我们可以知道,typesBySubscriber保存的是以GuideActivity.class为key,以List为value
        // 而subscribedEvents里面保存的又是eventType,即String.class
        // 最终的结论是:typesBySubscriber保存的是以对象为key,以被标记为@Subscribe方法里面带参的参数类型为值的集合为value
        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);
            }
        }
    }
// 保存对象以及SubscriberMethod
// 形象一点就是保存GuideActivity.class和GuideActivity类里面标记为@Subscriber方法的SubscriberMethod对象
final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
    /**
     * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
     * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
     */
    volatile boolean active;

    Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
        this.subscriber = subscriber;
        this.subscriberMethod = subscriberMethod;
        active = true;
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof Subscription) {
            Subscription otherSubscription = (Subscription) other;
            return subscriber == otherSubscription.subscriber
                    && subscriberMethod.equals(otherSubscription.subscriberMethod);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
    }
}

到这里我们的register()方法就结束了。

接下来进入到EventBus.getDefault.post();

// 有木有很熟悉的感觉,看过Handler源码的同学应该对这个很熟悉了吧
// ThreadLocal是为了保证线程安全的,在这里我就不做过多的说明了,不懂的同学可以自己去网上查查
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
         return new PostingThreadState();
    }
};

/** Posts the given event to the event bus. */
public void post(Object event) {
    // PostingThreadState这个类是干嘛用的呢?不要慌,点击进去看看
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    // 将事件加入到队列当中
    eventQueue.add(event);
    // 第一次进来肯定是false
    if (!postingState.isPosting) {
        // 判断事件发布是不是在主线程
        postingState.isMainThread = isMainThread();
        // 改变事件的状态,表示该事件已经被发布了
        postingState.isPosting = true;
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            // 哈哈哈哈,有木有很熟悉的感觉,在Handler源码里面MessageQueue也是通过一个while循环不断的去发布Message
             while (!eventQueue.isEmpty()) {
                 postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

// 我们可以把这个类理解为辅助类,主要是用来记录发布者线程状态
final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        // 注意,这里的event是你传递的值,比如像1,2,"12"等等
        // 拿到当前发布事件的类型(比如String.class)
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        // eventInheritance这个字段是干什么用的呢?
        // 比如 A extends B implements C  发布者post(A),那么找订阅者的时候不仅要找订阅了事件A的订阅者
        // 还要找订阅了B和C的订阅者
        if (eventInheritance) {
            // 找到事件的所有父类和所有实现的接口,以Class形式返回
            // 可能最终返回的结果是String.class,Message.class
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            // 遍历循环
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                // 注意这3个参数的意义
                // event:你传递的实际值,比如像1,2,"12"等等
                // postingState:记录发布者线程状态的实体类
                // clazz:拿到当前发布事件的实例,比如String.class,Message.class
                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));
            }
        }
} 
// 关键代理来了,好好看哟
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        // 还记得Subscription这个里面存了什么东西吗?
        // 实际上Subscription存储了两样东西,一个是Object subscriber(即GuideActivity.class),还有一个是标记为@Subscribe的方法封装的SubscriberMethod
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 在这里我以String.class为例
            // 拿出所有的以String.class为key的CopyOnWriteArrayList<Subscription>
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        // 当CopyOnWriteArrayList<Subscription>不为空的时候遍历集合
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 拿到集合里面的每一个Subscription
            for (Subscription subscription : subscriptions) {
                // 拿到Subscription里面的具体信息并赋值给PostingThreadState
                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;
}

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:// 在主线程,但是和MAIN的区别就是事件总是入队后交付给用户,所以调用后会立即返回
                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);
        }
}

这里我们稍微总结一下:在post()方法里面到底干了什么事情?其实就是一句话:

typesBySubscriber 找出满足需求的然后反射执行对应的方法

看到这里大家心里有没有点疑问呢?反正我是有的,具体是什么呢?大家可以好好揣摩一下我上面的那句话。

假设现在有这么一种情况:Activity1里面发布了一个test(String text)方法,Activity2里面也发布了一个test(String text)方法,然后我从Activity1跳转到Activity2,回退的时候执行post()方法,理论上Activity1和Activity2里面的test(String text)都应该被触发,但是这个时候Activity2已经被销毁了,那岂不是应用程序要闪退了?这个时候我们的unregister就闪亮登场了

接下来进入到EventBus.getDefault.unregister();

 /** Unregisters the given subscriber from all event classes. */
 // unregister代码很简单
public synchronized void unregister(Object subscriber) {
        // 判断当前类是否在Map<Object, List<Class<?>>> typesBySubscriber;
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        // 如果存在的话,首先从Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;移除该实例注册的所有订阅事件
        // 然后在Map<Object, List<Class<?>>> typesBySubscriber;中移除
        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--;
                }
            }
        }
} 

ungister()方法相对于其他方法来说还是比较简单的,我在这里给大家举一个例子大家就更明白了

首先我们要弄懂这两个Map里面到底是存放了些啥?不会总会感觉云里雾里的

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;

首先贴两张图

这里我再用文字描述一下:

1. Map<Class<?>, CopyOnWriteArrayList<Subscription>>

    1》存放的是以String.class,Message.class为key的(String.class,Message.class对应的是被@Subscribe标注的方法里面的参数类型)

     2》以CopyOnWriteArrayList<Subscription>为value的集合

2.CopyOnWriteArrayList<Subscription>里面的Subscription是一个实体类,里面包含了

final Object subscriber;
final SubscriberMethod subscriberMethod;

     1》subscriber代表的是register所在的那个类(比如:GuideActivity.class)

     2》subscriberMethod保存的是被@Subscribe标注的方法组合的实体类

3. Map<Object, List<Class<?>>> typesBySubscriber

     1》 key是register所在的那个类(比如:GuideActivity.class)

     2》 value是 List<Class<?>>集合,而Class<?> 对应的是被@Subscribe标注的方法里面的参数类型

 

看到这里你再回头看看unregister()方法,是不是so easy了

 

好了,到这里,EventBus的所有的源码就分析完了,其实回过头来看感觉也没有那么难,最重要的是静下心来好好看,边看边琢磨,多花点时间总可以搞懂的。最后以一句话结尾吧:天道酬勤,努力才会有收获!!!

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值