EventBus已经发展到第三版了,对于它的使用和原理相对于之前也有了很大的改进。下面就介绍一下EventBus2和EventBus3的使用和原理
说明:方法上面的参数设置
threadMode:线程工作状态,表示方法在哪个线程执行
ThreadMode.POSTING
:默认的设置,表示发送消息在哪个线程,就在哪个线程执行方法
ThreadMode.MAIN
:主线程执行该方法
ThreadMode.MAIN_ORDERED
:也是在主线程执行,只是不会阻塞主线程
ThreadMode.BACKGROUND
:后台线程执行
ThreadMode.ASYNC
:异步子线程
sticky:是否是粘性操作,表示如果方法在后面注册的话,也是可以收到消息的
priority:优先级,同一个消息,优先级高的优先收到消息
1、使用
1.1 EventBus2
1.1.1 EventBus2的配置
在app的build.gradle中进行配置
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
1.1.2 EventBus2的使用
注册:
需要在类中注册当前的对象,对象销毁的时候取消注册
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);//注册
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);//取消注册
}
//定义事件
@Subscribe(threadMode = ThreadMode.BACKGROUND,priority = 4)
public void onEvent(int click){
Log.e("MainActivity","onEvent"+click);
}
}
发送事件:
EventBus.getDefault().post(3);
EventBus.getDefault().postSticky(new Eventtype(3));//发送粘性事件
发送完事件之后就可以在Logcat中发现方法onEvent中打印的Log了。
1.2 EventBus3
1.2.1 EventBus3的配置
(1)导包
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
(2)配置索引文件属性,在build.gradle中进行配置
defaultConfig {
javaCompileOptions{
annotationProcessorOptions{
includeCompileClasspath = true
arguments = [
"eventBusIndex": "com.example.viewtest.EventBusIndex"]
}
}
}
(3)定义方法
在类中定义方法
@Subscribe(threadMode = ThreadMode.BACKGROUND,priority = 4)
public void onEvent(int click){
Log.e("MainActivity","onEvent"+click);
}
(4)编译
调用app的make project,就会生成对应的索引文件
(5)在application中进行注册
EventBus.builder().addIndex(new EventBusIndex()).installDefaultEventBus();
1.2.2 EventBus3的使用
基本操作都是一样的,也是需要注册和注销注册,发送事件
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
findViewById(R.id.tv_click).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new Eventtype(3));//发送消息
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.BACKGROUND,priority = 4)
public void onEvent(Eventtype click){
Log.e("MainActivity","onEvent"+click.click);
}
}
2、原理介绍
EventBus是实现跨线程通信的,那我们就要了解是如何实现跨线程的。
使用的模式就是观察者模式,先订阅消息,如果发生事件了,就回调订阅的方法。
下面我们就按照正常使用流程进行分析
2.1 订阅
使用的方法都是
EventBus.getDefault().register(this);
EventBus.getDefault()获取到EventBus单例对象。
注册的时候:
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
subscriberMethodFinder中查找是否已经注册过了
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
METHOD_CACHE 是一个对象,用来存储类对象和对应的添加了注解的需要EventBus处理的订阅方法表。
后面的逻辑就是如果存储过了就不需要存储了,直接返回即可。如果没有存储过,就需要重新添加一遍,这里就存在两种方式,一种是findUsingReflection(subscriberClass),代表之前EventBus2.0的方式,就是通过反射查找到类中的添加了注解的方法,然后添加到表中;
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
另一种就是findUsingInfo方法,EventBus3.0的方法,就是通过APT生成索引文件,然后通过索引文件查找到类中的添加了注解的方法,这样相对于反射速度更快,效率更高,并且索引文件是在编译时就生成的,这样不会影响运行时的效率,提升了性能。
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
通过getSubscriberInfo()方法获取到索引文件中的注册信息
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
这样就将所有注册的类中的添加了注解的方法存储完毕,等到发送消息时候就会遍历这个存储对象了。
当所有全部存储完之后,register方法中还需要走一步,就是调用订阅的方法
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
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;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
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>).
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方法就是主要是三部分的内容,一是将订阅事件和对应的要执行的方法存储在subscriptionsByEventType(Map<Class<?>, CopyOnWriteArrayList<Subscription>>对象)
中,存储链表的时候,还需要参考优先级,优先级高的放在前面;二是将类对象的注解方法参数添加到typesBySubscriber(Map<Object, List<Class<?>>>)
中,确认该类可以接收哪几种消息;三是粘性事件处理,如果当前方法是粘性的,就需要注解方法参数是否和之前的参数一致,如果一致那么就需要执行该方法。
2.2 发送消息
EventBus.getDefault().post(new Eventtype(3));
发送消息统一的方法就是调用EventBus的post方法,传递一个事件的对象。
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
上面方法的逻辑就是首先将消息添加到事件处理队列中,然后使用while 循环,调用postSingleEvent方法处理消息。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
lookupAllEventTypes()方法是用来查找所有的需要处理的事件类型,包括传入的EventType、他的父类和接口。找到类之后,postSingleEventForEventType方法查找对应的事件方法
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}
通过subscriptionsByEventType查找到对应的事件链表,执行链表中的每个方法,也就是调用 postToSubscription(subscription, event, postingState.isMainThread);方法,后面就是涉及跨线程通信的过程了。
2.3 跨线程通信
在postToSubscription方法中,是最后跨线程通信的部分,源码如下:
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case POSTING:
invokeSubscriber(subscription, event);
break;
case MAIN:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case MAIN_ORDERED:
if (mainThreadPoster != null) {
mainThreadPoster.enqueue(subscription, event);
} else {
// temporary: technically not correct as poster not decoupled from subscriber
invokeSubscriber(subscription, event);
}
break;
case BACKGROUND:
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
case ASYNC:
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
上面方法就是通过方法上面设置的threadMode参数,将方法放在哪个线程执行。一是默认当前线程,就直接通过反射执行该方法了;二是主线程,如果但是主线程,就直接执行该方法,如果不是,那就通过Handler发送到主线程进行执行;三也是主线程,同样的逻辑;四是后台线程,如果当前是主线程,那就将方法发送到后台线程队列中,然后通过EventBus线程池进行执行,如果当前不是主线程,那就直接执行;五是异步子线,直接发送到EventBus的线程池中进行执行。
说明:EventBus线程池是一种常用的缓存线程池,所以有消息的时候就会立刻进行处理。
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
到这里整个流程基本分析完毕了,没怎么讲的就是EventBus3中的索引文件生成过程,这个就是通过APT,编译时生成文件,现在基本大多数的框架都使用了这个框架,包括ARouter、Retrofit,这样有助于提高效率,避免使用反射。