MCPcopy
hub / github.com/greenrobot/EventBus / subscribe

Method subscribe

EventBus/src/org/greenrobot/eventbus/EventBus.java:159–207  ·  view source on GitHub ↗
(Object subscriber, SubscriberMethod subscriberMethod)

Source from the content-addressed store, hash-verified

157
158 // Must be called in synchronized block
159 private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
160 Class<?> eventType = subscriberMethod.eventType;
161 Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
162 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
163 if (subscriptions == null) {
164 subscriptions = new CopyOnWriteArrayList<>();
165 subscriptionsByEventType.put(eventType, subscriptions);
166 } else {
167 if (subscriptions.contains(newSubscription)) {
168 throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
169 + eventType);
170 }
171 }
172
173 int size = subscriptions.size();
174 for (int i = 0; i <= size; i++) {
175 if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
176 subscriptions.add(i, newSubscription);
177 break;
178 }
179 }
180
181 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
182 if (subscribedEvents == null) {
183 subscribedEvents = new ArrayList<>();
184 typesBySubscriber.put(subscriber, subscribedEvents);
185 }
186 subscribedEvents.add(eventType);
187
188 if (subscriberMethod.sticky) {
189 if (eventInheritance) {
190 // Existing sticky events of all subclasses of eventType have to be considered.
191 // Note: Iterating over all events may be inefficient with lots of sticky events,
192 // thus data structure should be changed to allow a more efficient lookup
193 // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
194 Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
195 for (Map.Entry<Class<?>, Object> entry : entries) {
196 Class<?> candidateEventType = entry.getKey();
197 if (eventType.isAssignableFrom(candidateEventType)) {
198 Object stickyEvent = entry.getValue();
199 checkPostStickyEventToSubscription(newSubscription, stickyEvent);
200 }
201 }
202 } else {
203 Object stickyEvent = stickyEvents.get(eventType);
204 checkPostStickyEventToSubscription(newSubscription, stickyEvent);
205 }
206 }
207 }
208
209 private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
210 if (stickyEvent != null) {

Callers 1

registerMethod · 0.95

Calls 2

getMethod · 0.45

Tested by

no test coverage detected