Android-EventBus底层原理浅析(三)

上两节的内容分别是:
一 注册的底层逻辑 https://www.jianshu.com/p/e324c8353fe8
二 发送事件的底层逻辑 https://www.jianshu.com/p/8c78419dc654

这节咱们讲注销,其实很简单,但为什么我还要另开一篇写呢,强迫症啊不给啊哼!

老规矩,上代码

EventBus.getDefault().unregister(this)

好的,进入unregister方法

public synchronized void unregister(Object subscriber) {
 1        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
 2               unsubscribeByEventType(subscriber, eventType);
            }
 3           typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

1:还记得typesBySubscriber这个对象吗,我们在注册的时候最后以订阅者为Key,参数集合为value给保存了起来,如下

typesBySubscriber.put(subscriber, subscribedEvents);

这个时候派上用场了,我们在代码传入了this,查询出对应的订阅方法的参数集合
2:遍历参数集合,调用unsubscribeByEventType()方法做进一步注销处理
3:将自身从typesBySubscriber这个对象移除

进入 unsubscribeByEventType(subscriber, eventType)

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
1        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);
2               if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

1:subscriptionsByEventType对象熟悉吗,就是我们注册时候以事件类型为key,订阅者集合为value保存起来的对象,如下

CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
...
subscriptionsByEventType.put(eventType, subscriptions);

所以这里根据事件类型将订阅者集合给拿了出来
2:遍历订阅者集合,一个个检查身份,如果是当前传入的订阅者(unregister(this)方法的this),则从集合里抹除

ok,注销没了!就酱紫!就是对subscriptionsByEventType跟typesBySubscriber这两个对象的操作,前面的注册流程比较绕的也是将数据放进subscriptionsByEventType跟typesBySubscriber,只要你理解了就不难了(一个类可以有多个订阅方法,一个事件类型也可以有多个订阅类跟方法,所以subscriptionsByEventType的key是事件类型,typesBySubscriber的key是订阅类)

要不,有空再补上个粘性事件?感觉字数有点少的呢。

推荐阅读更多精彩内容