事件总线EventBus
为了简化并提高在activity、Fragment、Thread和Service之间的通信,同时解决组件之间的高耦合的同时仍然能继续高效地通信,事件总线设计出现了。著名的开源框架有EventBus和otto,我们先来解析EventBus。
一、EventBus简介
EventBus是针对Android优化的发布–订阅事件总线。它简化了应用程序内各组件、组件与后台线程间的通信。优点是开销小、代码优雅。以及将发布者和订阅者解耦。我们知道在平时的开发中Activity和Activity的交互还好说,但是Fragment与Fragment之间的交互就复杂的多。这时候我们会用广播来处理,但是使用广播效率也不高。
二、使用EventBus
EventBus的三要素和它的四中ThreadMode。
三要素:
- a,Event:事件,可以是任意类型的对象
- b,Subscriber:事件订阅者。在EventBus 3.0之前消息处理方式只能限定于onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,分别代表四种线程模型。在EventBus 3.0之后,事件处理的方法可以随便取名,但是需要添加一个注解@Subscribe,并且要指定线程模型(默认为POSTING)。
- c,Publisher:事件发布者。可以在任意线程任意位置发送事件,直接调用EventBus的post(Object)方法,可以自己实例化EventBus对象,但一般使用EventBus.getDefault()就可以。根据post函数参数的类型,会自动调用订阅相应类型事件的函数。
四种ThreadMode(线程模型)。
四模型:
- 1,POSTING(默认):该模型下,该事件是在哪个线程发布出来的,事件处理函数就会在哪个线程中运行,也就是说事件发布和订阅事件在同一个线程中。在此模型状态下应该注意尽量避免处理函数中执行耗时操作,因为它会阻塞事件的传递,甚至引起ANR。
- 2,MAIN:事件处理在UI线程,事件处理事件不能太长,否则会引起ANR。
- 3,BACKGROUND:此模式下,若事件是从UI线程发出来的,那么事件处理函数就会在新的线程中运行:若本来就是在子线程中发布出来的,那么该事件处理函数就直接在发布事件的线程执行。在此事件处理函数中禁止进行UI操作。
- 4,ASYNC:此模式下,无论在哪个线程发布事件,该事件处理函数都会在新建的子线程中进行,同样,事件处理函数也禁止进行UI更新操作。
2.1 EventBus的用法
分为步骤:
1,自定义一个事件类
1
2
3public class MessageEvent {
}2,在需要订阅的地方注册事件:
1
Event.getDefault().rigister(this);
3,发送事件
1
EventBus.getDefault().post(messageEvent);
4,处理事件
1
2
3
4@Subscribe (tthreadMode = Thread.MAIN)
public void XXX (MessageEvent messageEvent) {
//code
}5,取消订阅事件
1
Event.getDefault().unregister(this);
注:消息方法可以随意取名,但是需要添加一个注解@Subscribe,并且要指定线程模型(默认为POSTING)。
2.2 EventBus应用举例
2.2.1 添加依赖库1
implementation 'org.greenrobot:eventbus:3.1.1'
现在已经更新到3.1.1版本。
2.2.1 定义消息类事件1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class MessageEvent {
private String message;
public MessageEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2.2.3 注册和取消订阅1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42public class MainActivity extends AppCompatActivity {
private TextView tv_message;
private Button bt_message;
private Button bt_subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_message = this.findViewById(R.id.tv_message);
tv_message.setText("MainActivity");
bt_subscription = this.findViewById(R.id.bt_subscription);
bt_subscription.setText("注册事件");
bt_message = this.findViewById(R.id.bt_message);
bt_message.setText("跳转到secondactivity");
bt_message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
bt_subscription.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//注册事件
EventBus.getDefault().register(MainActivity.this);
}
});
}
//事件处理者处理事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMoonEvent(MessageEvent messageEvent){
tv_message.setText(messageEvent.getMessage());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
我们定义了两个Button和TextView,Button用来注册和跳转到另一个Activity,TextView用来显示内容。
2.2.4 事件订阅者处理事件
在MainActivity中定义方法来处理事件,在这里因为ThreadMode为MAIN,事件的处理会在UI线程中执行,用TextView来展示收到的信息。1
2
3
4@Subscribe(threadMode = ThreadMode.MAIN)
public void onMoonEvent(MessageEvent messageEvent){
tv_message.setText(messageEvent.getMessage());
}
2.2.5 事件发布者发布事件
SecondActivity中的代码如下所示:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public class SecondActivity extends AppCompatActivity {
private Button bt_message;
private Button bt_message1;
private TextView tv_message;
@Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sec);
tv_message = findViewById(R.id.tv_message);
tv_message.setText("SecondActivity");
bt_message = findViewById(R.id.bt_message);
bt_message.setText("发送事件");
bt_message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new MessageEvent("欢迎"));
finish();
}
});
}
}
在SecondActivity中,定义”发送事件”来发送事件并将SecondActivity finish掉,运行程序,如下图所示。
接下来点击”注册事件”按钮来注册事件,然后点击下面的按钮跳转到SEcondActivity,这时候跳转到SecondActivity,如下图所示,接下来点发送事件按钮,这是SecondActivity会被finish掉,这时候MainActivity的TextView会显示”欢迎”。
注:以上代码是这个程序后续都写好了运行截图的,所以后续的黏性事件的代码也显示了,懒得改了
2.3 EventBus的粘性事件
EventBus还支持发送黏性事件,就是在发送事件之后再订阅该事件也能收到该事件,这类似黏性广播。我们看怎么修改代码。
2.3.1 订阅者处理黏性事件
在MainActivity中写一个方法来处理黏性事件。1
2
3
4
5代码位于MainActivity中
@Subscribe(threadMode = ThreadMode.POSTING,sticky = true)
public void ononMoonSticky (MessageEvent messageEvent) {
tv_message.setText(messageEvent.getMessage());
}
2.3.2 发送黏性事件
1 | 代码位于SecondActivity中 |
运行代码,我们在MainActivity没有点注册按钮,而是直接进入到SecondActivity中,然后选择发送黏性事件,这时回到MainActivity,我们看到在MainActivity仍然显示”MainActivity”,点击”注册事件”,TextView内容发生了变化,显示”黏性事件”,说明黏性事件被接收到了。
三、源码解析EventBus
3.1 EventBus构造方法
EventBus.getDefault()方法,可以看到这是一个经典的单例模式,还是DCL单例。1
2
3
4
5
6
7
8
9
10public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
再看EventBus()构造函数:1
2
3public EventBus() {
this(DEFAULT_BUILDER);
}
DEFAULT_BUILDER是默认的EventBusBuilder,用来构造EventBus。这里this是调用了Eventbus的另一个有一个参数的构造方法。我们再看这个有一个DEFAULT_BUILDER参数的构造方法。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
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;
}
可以看到,我们可以通过一个EventBusBuilder来构造EventBus,这里应用了建造者模式。
3.2 订阅者注册
获取EventBus实例后,便可以将订阅者注册到EventBus中,看rigister方法。1
2
3
4
5
6
7
8
9public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//1
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);//2
}
}
}
对于以上代码解析:
1,查找订阅者的订阅方法
在注释1处的findSubscriberMethods方法找出一个SubscribeMethod集合,也就是传进来的订阅者的所有订阅方法,接下来遍订阅者历所有的订阅方法来完成订阅者的注册操作。register做了两件事:一是查找订阅者的订阅方法,二是订阅者的注册,SubscriberMethod类用来保存订阅方法的Method对象、线程模型、事件类型、优先级、是否是黏性事件一系列属性。findSubscriberMethods代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);//1
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);//3
}
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);//2
return subscriberMethods;
}
}findUsingInfo方法,在项目中通常是通过EventBus单例模式来获取默认的EventBus对象,也就是ignoreGeneratedIndex为false的情况,这时候就会调用findUsingInfo方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);//1
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();//2
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
findUsingReflectionInSingleClass(findState);//3
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}注释1处:通过getSubscriberInfo方法获取订阅者的信息,在开始查找订阅方法的时候并没有忽略注释器为我们生成的索引MyEvenBusIndex。如果我们通过EventBusBuilder配置了MyEvenBusIndex,便会获取subscriberInfo。就会调用subscriberInfo的getSubscriberMethods方法,获取订阅方法相关的信息;若没有配置MyEvenBusIndex,就执行3处的findUsingReflectionInSingleClass方法,将订阅方法保存到findState中。最后通过getMethodsAndRelease方法对dindState做回收处理并返回订阅的List集合。默认是没有配置MyEvenBusIndex的,所以看看findUsingReflectionInSingleClass的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
//通过反射来获取订阅者中所有方法
// This is faster than getMethods, especially when subscribers are fat classes like Activities
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}2,订阅者的注册过程
在rigister方法中,在注释2处调用了subscribe方法来对订阅方法进行注册,如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//1
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//2
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);
}
}
}
3.3 事件的发送
获取EventBus对象后,可以通过post方法来进行事件的提交。post源码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public void post(Object event) {
//PostingThreadState保存着事件队列和线程状态信息
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;
}
}
}
分析:首先从PostingThreadState对象中取出事件队列,然后再讲当前的事件插入事件队列。最后将队列中的事件一次交由postSingleEvent方法处理,并移除该事件。之后看postSingleEvent方法里做了什么:
postSingleEvent1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//eventInheritance表示是否向上查找事件的父类,默认为true
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));
}
}
}
eventInheritance表示是否向上查找事件的父类,它的默认值是true,可以通过在EventBusBuilder中进行配置。当eventInheritance为true,则通过lookupAllEventTypes找到所有父类事件并存在List中,然后通过postSingleEventForEventType方法逐一处理,postSingleEventForEventType代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//同步取出该事件对应的Subscription(订阅对象集合)
subscriptions = subscriptionsByEventType.get(eventClass);//1
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {//2
//处理Subscription,将事件event和Subscription(订阅对象)传递给postingState并调用postToSubscription方法对事件进行///处理
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;
}
注释1处同步取出该事件对应的Subscription(订阅对象集合),注释2处处理Subscription,将事件event和Subscription(订阅对象)传递给postingState并调用postToSubscription方法对事件进行,接下来看postToSubscription源码:
postToSubscription:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34private 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之后,根据threadMode来分别处理,若threadMode是MAIN,则通过反射直接运行订阅的方法;若不是主线程,则需要mainThreadPoster将我们的订阅事件添加到主线程队列中。mainThreadPoster是HandlerPoster类型的,继承自Handler,通过Handler将订阅的方法切换到主线程。
3.4 订阅者取消注册
unrigister方法:1
2
3
4
5
6
7
8
9
10
11
12/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);//1
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);//2
}
typesBySubscriber.remove(subscriber);//3
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
typesBySubscriber是一个map集合,注释1处通过subscriber找到subscribedTypes(事件类型集合)。注释3处将subscriber对应的eventType从typesBySubscriber中移除。注释2处遍历subscribedTypes,并调用unsubscribeByEventType方法:
unsubscribeByEventType源码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//1
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
注释1处通过eventType来得到对应的Subscription(订阅对象集合),并在for循环中判断如果Subscription(订阅对象)的subscriber属性等于传进来的subscriber,则从Subscription中移除该Subscription。
这就是EventBus的源码