1、主要内容
EventBus
Subscription
SubscriberMethodFinder
ExecutorService
AsyncPoster
PendingPost
HandlerPoster
android-apt是什么?
android-apt 是一个Gradle插件,协助Android Studio 处理annotation processors, 它有两个目的:
允许配置只在编译时作为注解处理器的依赖,而不添加到最后的APK或library
设置源路径,使注解处理器生成的代码能被Android Studio正确的引用
在app的build.gradle中的 dependencies 中还需要配置eventbus-annotation-processor
apply plugin: 'com.neenbedankt.android-apt'
....
apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
...
apt {
arguments {
eventBusIndex "com.xxx.XEventBusIndex"
}
}
...
//在application中将ebindex
EventBus.builder().addIndex(new XEventBusIndex()).installDefaultEventBus();
1、Eventbus
单例模式: 获取eventbus 工具类
public static EventBus getDefault() {
if(defaultInstance == null) {
Class var0 = EventBus.class;
synchronized(EventBus.class) {
if(defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
2、注册:
注册的处理逻辑
1、根据注册的订阅者获取到class,根据class通过findSubscriberMethods 查找到 Annotation 为Subscribe的method,缓存起来 SubscriberMethod
Subscribe methodName1 = (Subscribe)method.getAnnotation(Subscribe.class);
public void register(Object subscriber) {
Class subscriberClass = subscriber.getClass();
List subscriberMethods = this.subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized(this) {
Iterator var5 = subscriberMethods.iterator();
while(var5.hasNext()) {
SubscriberMethod subscriberMethod = (SubscriberMethod)var5.next();
this.subscribe(subscriber, subscriberMethod);
}
}
}
3、post 发送逻辑:
通过event 查找 event 的订阅者,判断线程状态,最后调用: this.invokeSubscriber(subscription, event); ,如果是异步线程,通过线程池执行AsyncPoster 执行 ,如果运行在主线程,但是post线程非主线程需要通过HandlerPoster切换调用线程。
public void post(Object event) {
EventBus.PostingThreadState postingState = (EventBus.PostingThreadState)this.currentPostingThreadState.get();
List eventQueue = postingState.eventQueue;
eventQueue.add(event);
if(!postingState.isPosting) {
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if(postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while(!eventQueue.isEmpty()) {
this.postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
.......
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch(null.$SwitchMap$org$greenrobot$eventbus$ThreadMode[subscription.subscriberMethod.threadMode.ordinal()]) {
case 1:
this.invokeSubscriber(subscription, event);
break;
case 2:
if(isMainThread) {
this.invokeSubscriber(subscription, event);
} else {
this.mainThreadPoster.enqueue(subscription, event);
}
break;
case 3:
if(isMainThread) {
this.backgroundPoster.enqueue(subscription, event);
} else {
this.invokeSubscriber(subscription, event);
}
break;
case 4:
this.asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}