EventBus3.0源码分析

EventBus3.0源码分析

从3.0开始用了更多注解事件的订阅方法来代替之前固定onEvent开头的方法。现在你可以是容易方法加上@Subscribe的注解。

更多的eventbus使用方法请看http://www.jianshu.com/p/c47e0900399e

EventBus.java

  1. EventBus类的创建使用了常见的单例模式,如下:
1
2
3
4
5
6
7
8
9
10
11
static volatile EventBus defaultInstance; //volatile 修饰的变量防止被编译器优化,导致执行顺序变化
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
  1. 使用了建造者模式给变量赋值。先在EventBus的构造方法创建EventBusBuilder ,再重载过的EventBus方法传入builder来配置一些变量(比如一些exception)。如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
  1. 在register中,获取订阅者的类subscriberClass通常是activity和fragment。然后通过subscribeerMethodFinder获取订阅者上订阅方法返回一个list集合。其中subscriberMethod就是写在activity上拿来接受消息的方法的对象,里面的变量包括Method就可以知道方法名;eventType可以知道是ativity还是fragment;threadMode是哪个线程;sticky是否粘性事件;priority优先级系数多少。如下:
1
2
3
4
5
6
7
8
9
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}