// Must be called in synchronized block privatevoidsubscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority){ Class<?> eventType = subscriberMethod.eventType; //根据事件类型取出该类事件的所有订阅者 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority); if (subscriptions == null) {//如果没有该类型的订阅者 创建一个 加入列表 subscriptions = new CopyOnWriteArrayList<Subscription>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) {//如果所有订阅者中已经包含新加入的这个订阅者,提示已经订阅了 thrownew 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(); //遍历所有的订阅者 按照优先级(Subscription的priority属性)进行排序 for (int i = 0; i <= size; i++) { if (i == size || newSubscription.priority > subscriptions.get(i).priority) { subscriptions.add(i, newSubscription); break; } }
//取出某个订阅者中所有的订阅事件 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<Class<?>>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType);
if (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); } } }
当subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority)方法执行完之后,所有的订阅者以及订阅者中的事件接受方法就被存起来了。