# Only required if you use AsyncExecutor -keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent { <init>(java.lang.Throwable); }
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus(); // Now the default instance uses the given index. Use it like this: EventBus eventBus = EventBus.getDefault();
源码解析
注册流程
1 2 3 4 5 6 7 8 9 10 11
/** Convenience singleton for apps using a process-wide EventBus instance. */ publicstatic EventBus getDefault(){ if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }
getDefault使用单例模式,保证整个app只有唯一实例。初次进入会进入无参构造中初始化
1 2 3 4 5 6 7
/** * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a * central bus, consider {@link #getDefault()}. */ publicEventBus(){ this(DEFAULT_BUILDER); }
1
privatestaticfinal EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus installDefaultEventBus(){ synchronized (EventBus.class) { if (EventBus.defaultInstance != null) { thrownew EventBusException("Default instance already exists." + " It may be only set once before it's used the first time to ensure consistent behavior."); } EventBus.defaultInstance = build(); return EventBus.defaultInstance; } }
1 2 3
public EventBus build(){ returnnew EventBus(this); }
privatevoidsubscribe(Object subscriber, SubscriberMethod subscriberMethod){ //获取订阅事件 Class<?> eventType = subscriberMethod.eventType; Subscription newSubscription = new Subscription(subscriber, subscriberMethod); //private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; //获取该事件类型对应的所有订阅者信息(Subscription) CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) { //如果信息为null,初始化subscription,将该订阅信息放入其中 subscriptions = new CopyOnWriteArrayList<>(); subscriptionsByEventType.put(eventType, subscriptions); } else { //如果信息不为null,map中包含该订阅信息,则报错,已经被注册了 if (subscriptions.contains(newSubscription)) { thrownew EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } }
//根据priority优先级插入订阅信息subscriptions中 int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription); break; } } // private final Map<Object, List<Class<?>>> typesBySubscriber; //根据订阅者,从typeBySubscriber中取出订阅者事件类型 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { //创建一个空的事件类型集和放入typesBySubscriber subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } //将事件类型的class对象放入subscribedEvents subscribedEvents.add(eventType); ..... }
1 2 3 4 5 6 7 8 9 10
finalclassSubscription{ final Object subscriber; final SubscriberMethod subscriberMethod; /** * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions. */ volatileboolean active; ... }
privatevoidsubscribe(Object subscriber, SubscriberMethod subscriberMethod){ ... //如果是粘性事件 if (subscriberMethod.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>). //private final Map<Class<?>, Object> stickyEvents; //stickyEvents存储具体的粘性事件 //map变化为set Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); //循环遍历 for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); //判断candidaetEventType是否为eventType的子类 if (eventType.isAssignableFrom(candidateEventType)) { Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
privatevoidcheckPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent){ 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, isMainThread()); } }
publicvoidpostSticky(Object event){ synchronized (stickyEvents) { //将粘性事件放置在stickyEvents中 stickyEvents.put(event.getClass(), event); } // Should be posted after it is putted, in case the subscriber wants to remove immediately //执行post方法 post(event); }