代码里面注销eventbus一般我们会在onDestory里面这么写:
- 1 EventBus.getDefault().unregister(this);
然后走到unregister里面去看看:
-
1 /** 2 * @param subscriber 3 */ 4 public void unregister(Object subscriber) { 5 if (subscriber == null) { 6 return; 7 } 8 synchronized (this) { 9 mMethodHunter.removeMethodsFromMap(subscriber); 10 } 11 }
然后往
mMethodHunter
.
removeMethodsFromMap
(
subscriber
);里面走:
mSubcriberMap是存储的map集合;
CopyOnWriteArrayList<Subscription>是mSubcriberMap map集合的value,是个存储订阅者对象的list集合;
Subscription为
订阅者对象,包含订阅者和目标方法;
遍历订阅者对象的list集合,移除集合里面指定的Subscription引用;
如果
CopyOnWriteArrayList
<
Subscription
>的list集合为null或者长度为0,从而从map中进行删除操作,操作就是先删除订阅者,继而删除map集合里面的内容,list和map相互关联。
1 /** 2 * remove subscriber methods from map 3 * 4 * @param subscriber 5 */ 6 public void removeMethodsFromMap(Object subscriber) { 7 //获取map值value的list迭代器 8 Iterator<CopyOnWriteArrayList<Subscription>> iterator = mSubcriberMap 9 .values().iterator(); 10 //遍历集合 11 while (iterator.hasNext()) { 12 CopyOnWriteArrayList<Subscription> subscriptions = iterator.next(); 13 //如果集合不为null 14 if (subscriptions != null) { 15 List<Subscription> foundSubscriptions = new 16 LinkedList<Subscription>(); 17 //Subscription 订阅者对象,包含订阅者和目标方法 18 Iterator<Subscription> subIterator = subscriptions.iterator(); 19 while (subIterator.hasNext()) { 20 //获取Subscription对象 21 Subscription subscription = subIterator.next(); 22 // 获取引用 23 Object cacheObject = subscription.subscriber.get(); 24 if (isObjectsEqual(cacheObject, subscriber) 25 || cacheObject == null) { 26 Log.d("", "### 移除订阅 " + subscriber.getClass().getName()); 27 //foundSubscriptions添加Subscription对象引用 28 foundSubscriptions.add(subscription); 29 } 30 } 31 // 移除该subscriber的相关的Subscription[即map集合里面值value里面指定的list的某一项,此处进行遍历删除] 32 subscriptions.removeAll(foundSubscriptions); 33 } 34 // 如果针对某个Event的订阅者数量为空了,那么需要从map中清除 35 if (subscriptions == null || subscriptions.size() == 0) { 36 iterator.remove(); 37 } 38 } 39 }