EventBus笔记--源码--注销
2017-08-02 本文已影响74人
MinuitZ
有了前面的源码阅读 , 注销其实我们自己不用看都知道是怎么回事了: 只需要在map集合中吧订阅者相关的数据移除掉就可以了 , 也就是要对那两个集合操作了.
EventBus -- 基本使用
EventBus源码 -- 注册
EventBus源码 -- 发送消息
EventBus源码 -- 注销
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 {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
得到订阅者之后 , 根据事件类型和订阅者解绑
unsubscribeByEventType(subscriber, eventType);
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的注销结束.