继续 register中的方法,for 循环 扫描到的所有方法,然后调用 subscribe
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
subscribed = true;
Class<?> eventType = subscriberMethod.eventType;
// 根据 subscriberMethod.eventType ,在 subscriptionsByEventType 中查找
// CopyOnWriteArrayList<Subscription>,如果没有则创建
// subscriptionsByEventType 是 Map集合,用于存储EventBus所有方法的地方
// key: eventType,value: CopyOnWriteArrayList<Subscription>
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 把 传入的参数封装成 Subscription(subscriber, subscriberMethod, priority) 对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
for (Subscription subscription : subscriptions) {
if (subscription.equals(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true);
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
// 添加 newSubscription,优先级高的 添加到 list集合前边
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 根据 subscriber 存储 所有的 eventType
// subscribedEvents是 Map 集合,key:subscriber value: List<eventType>
subscribedEvents.add(eventType);
// 判断 sticky:如果为true,从 stickyEvents 中 根据 eventType查找有没有 stickyEvent
// stickyEvent 就是 post(javabean)中传递的参数,
// 如果有就调用 postToSubscription,发布
if (sticky) {
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
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, Looper.getMainLooper() == Looper.myLooper());
}
}
} |